python - Access local classvariable from inherited instance -


I have a pseudo-interface, which I apply several times. Each implementation should store a variable that basically defines the path for a file (a template). Because these sections are produced by a factory, I do not know how the subclass is running, therefore, I want to make it possible to use a class variable through an example method.

This is not really a problem, however, when I get from my interface, I do not want to apply the code to getHidden () many times. But it is calling, the way it is written below, it will always be hidden preform> class MySuperInterface: # class variable __much = "hidden" # Example method def getHidden ( Self): Print self.__ class_____ very high class MySub (MySuperInterface): __much = "It is different per subclass!" DEF is very upset (self): print itself .__ class __.__ lot < / pre>

execution

  & gt; & Gt; & Gt; Sub = MySub () # I do not know this class! & Gt; & Gt; & Gt; Sub.getHidden () Hidden & gt; & Gt; & Gt; Sub.soTroublesome () This is different according to sub-category!   

So, how can I use getHidden () to classify class of example. I know, that information is available, as I have checked with dir () , but I do not know how to access it.

Thank you!

simply class Do not use "__" in the variable name and you are set.

Some python write-ups and "documentation" say that the "__" prefix is ​​the Python method of obtaining "private" members in a class. They are wrong .

The "__" prefix ensures what is happening to you: Make sure that the variable that exact class (and those used in any method inside the class) None of the classes who get it from it).

The way this works works is simple: compile at the time, the prefix name with "__" is "complicated", that is, has been changed in such a way: __ lot -> _classname__ more :

  & gt; & Gt; & Gt; Class hidden (object): ... __hidden = False ... & gt; & Gt; & Gt; DIR (hidden) ['_Hidden__hidden', '__class__', ...]   

So your has been found method always __ more The name of the variable has actually been renamed to _MySuperInterface__much , while the variable you want has been renamed to _MySub__much .

If you are using a single underscore "_" to insert as much, the variable should not be used outside the classroom, your code will work as you expect.

Comments

Popular posts from this blog

Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

multithreading - PhantomJS-Node in a for Loop -

c++ - MATLAB .m file to .mex file using Matlab Compiler -