Skip to content

Instantly share code, notes, and snippets.

@dews
Last active October 30, 2018 08:17
Show Gist options
  • Save dews/e0a568f7e4a023555319b05adbcc46f2 to your computer and use it in GitHub Desktop.
Save dews/e0a568f7e4a023555319b05adbcc46f2 to your computer and use it in GitHub Desktop.
python inheritance share variable
class Parent():
i = 123
def assign(self, n):
self.i = n
class ChildA(Parent):
def f1(self):
Parent.assign(self, 1)
print("self:", self.i)
def f2(self):
print("self:", self.i)
class ChildB(Parent):
def f1(self):
Parent.assign(self, 2)
print("self:", self.i)
ChildA = ChildA()
ChildA.f2()
ChildA.f1()
ChildB = ChildB()
ChildB.f1()
ChildA.f2()
print(ChildA.i)
# RESULT:
# self: 123
# self: 1
# self: 2
# self: 1
# 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment