Skip to content

Instantly share code, notes, and snippets.

@liweinan
Last active April 1, 2018 14:54
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 liweinan/93f5ffea17a5d25bb438e5a9b230361e to your computer and use it in GitHub Desktop.
Save liweinan/93f5ffea17a5d25bb438e5a9b230361e to your computer and use it in GitHub Desktop.
class Dog2:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
dogX = Dog2("Yanan")
dogY = Dog2("Anan")
print("-=CLASS VARIABLE=-") # 这个kind是保存在class里的
print("Dog2.kind: " + Dog2.kind)
print("-=INSTANCES=-")
print("dogX.name: " + dogX.name) # name是每个instance都会各自保存的
print("dogY.name: " + dogY.name)
print("dogX.kind: " + dogX.kind) # 实际是class variable,所以从instance里面取出来也是class里面的
print("dogY.kind: " + dogY.kind)
print("-=RESET CLASS VARIABLE=-")
Dog2.kind = "hahaha" # 因为是class variable,所以改动以后,各个instances查看的时候也就跟着变了,因为实际只有class里面保存一份
print("dog2.kind(): " + Dog2.kind)
print("dogX.kind(): " + dogX.kind)
print("dogY.kind(): " + dogY.kind)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment