python - Getting parent private or protected values from the child class -
well, have same question, except 1 detail: need private values of base of operations class. code:
class parent(object): def __init__(self): self.__field = 13 class child(parent): """docstring child""" def __init__(self): super(child, self).__init__() def childmethodwhichusingparentfield(self): homecoming self.__field if __name__ == '__main__': c = child() c.childmethodwhichusingparentfield() interpreter output:
traceback (most recent phone call last): file "foo.py", line 20, in <module> c.childmethodwhichusingparentfield() file "foo.py", line 16, in childmethodwhichusingparentfield homecoming self.__field attributeerror: 'child' object has no attribute '_child__field' the problem interpreter tries _child__field when need _parent__field. can value using @property, brake encapsulation. can solve problem writing self._parent__field ugly , bad code. there other ways?
as have noted in question, can access parent attribute explicitly using mangled form of name in kid class:
def childmethodwhichusingparentfield(self): homecoming self._parent__field this simple reply direct question.
however, if have command on parent class, bad design. should not utilize double-underscore attribute name class class ever utilize (and shouldn't utilize if don't expect such use). utilize single underscore (_field) instead. "documents" attribute intended private (e.g. not part of class's public api), without enabling name mangling. way, if find later class need access variable can. python doesn't enforce privacy (not when name mangling used), you'll need rely upon other code behaving nicely.
name mangling intended utilize in situations need avoid name collisions. instance, proxy object might utilize mangled names own attributes can nowadays interface exact replica of object's interface (which may not known ahead of time). or mixin class might utilize name mangling variables since can't know sure attribute names used in (possibly many) other classes inherited along side it. can useful if you're adding attribute own utilize other objects (not self) , want avoid overwriting existing attributes mistake.
python oop inheritance
No comments:
Post a Comment