Skip to content

Instantly share code, notes, and snippets.

@codekiln
Created June 4, 2018 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codekiln/600184f955ec83037fb6142660a482a8 to your computer and use it in GitHub Desktop.
Save codekiln/600184f955ec83037fb6142660a482a8 to your computer and use it in GitHub Desktop.
Testing self.__variables, class.__variables and inheritance in Python
class ParentClass(object):
__special = ''
def __init__(self, *args, **kwargs):
self.__class__.__special = 'ParentClass'
self.__special = 'ParentClass'
print self.__dict__
def special(self):
return self.__special
@classmethod
def special_class(cls):
return cls.__special
class ChildClassOne(ParentClass):
def __init__(self, *args, **kwargs):
self.__special = 'ChildClassOne'
super(ChildClassOne, self).__init__(*args, **kwargs)
class ChildClassTwo(ParentClass):
def __init__(self, *args, **kwargs):
self.__doc_type = 'ChildClassTwo'
# try commenting this line out, it's an attribute error
self.__class__.__special = 'ChildClassTwo'
super(ChildClassTwo, self).__init__(*args, **kwargs)
def special(self):
return self.__doc_type
@classmethod
def doc_type_class(cls):
return cls.__special
if __name__ == '__main__':
parent_class = ParentClass()
child_class_one = ChildClassOne()
child_class_two = ChildClassTwo()
"""
{'_ParentClass__special': 'ParentClass'}
{'_ChildClassOne__special': 'ChildClassOne', '_ParentClass__special': 'ParentClass'}
{'_ParentClass__special': 'ParentClass', '_ChildClassTwo__special': 'ChildClassTwo'}
"""
print ""
print ParentClass.special_class()
print ChildClassOne.special_class()
print ChildClassTwo.special_class()
"""
ParentClass
ParentClass
ChildClassTwo
"""
print ""
print parent_class.special()
print child_class_one.special()
print child_class_two.special()
"""
ParentClass
ParentClass
ChildClassTwo
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment