I was wondering if it is possible to get a list of static variables in the class, while respecting heritage.
I have a code snippet that gives a key-value dictionary of all the static variables within a class:
dict = {attr: class.__ dict __ [Attr] for class in attr .__ dict__ if not callable (getattr (class, atri)) and not attr.startswith ('__')}
The issue is that It only gives the declared variable variable within that specific class, but not inherited from its original class. For example:
class (): var1 = 1 def __init __ (self) : Pass Class Sub-Class (A) Rsha): var2 = 2 def __init __ (self): super () .__ init __ () that __name__ == '__main__': dict1 = {Attr class. ATR] for class at .__ dict__ if not callable (getattr (class, etter)) and not attr.startswith ('__')} dict2 = {Attr: subclass .__ __ for entry in subtitles __ [atri ] .__ If the duct is not callable (gator (all class, et)) and not attr.startswith ('__')} print (dict1) print (dict2) print ('class: var1 = {}' format. (Class. 1)) print ('subclass: var1 = {}, var2 = {}'. Format (subclass. 1, subclass.v2))
returns < / P>
{'var1': 1} {'var2': 2} class: var1 = 1 sub-work : Var1 = 1, var2 = 2
I was thinking of getting a dictionary for the base class and inserting it with the subclass dictionary, but I'm not sure how many Legacy is needed and I want to avoid unnecessary headaches.
Is there an Ea way, which I have suggested above, apart from obtaining a key-value dictionary of all static variables within a class, which are included in the heritage?
Maybe dir
the built-in function will be appropriate, if you are actually only steady variable Note about:
# python 2.7.6 square A (object): a_static_var = 'a constant var' square b (a): b_staty_over = 'b static ve' print dyer (B)
Print:
['__sc__', ... & lt; Etc & gt; ..., 'a_static_var', 'b_static_var']
To get the dictionary of static variables their values (any startwith ('_') < Instead of using / p>
may recommend a better method for filtering values. -Calable, non-personal static variables and their value for static_var_vals = {} att in dir (B): if Not attr_name.startswith ('_'): attr = getattr (b, attr_nam) e): if not valid: static_var_vals [attr_name] = atr
Comments
Post a Comment