class CC:
def setXY(self,x,y):
self.x=x
self.y=y
def printXY(self):
print(self.x,self.y)
dd=CC()
print(dd.__dict__) # {} #对象CC()的所有成员
print(CC.__dict__) #{'__weakref__': <attribute '__weakref__' of 'CC' objects>, '__doc__': None, '__dict__': <attribute '__dict__' of 'CC' objects>, 'printXY': <function CC.printXY at 0x0000000000A50268>, '__module__': '__main__', 'setXY': <function CC.setXY at 0 #输出类CC的所有成员
dd.setXY(4,5)
print(dd.__dict__) #{'y': 5, 'x': 4}#赋值后类对象有值了
print(CC.__dict__) #{'printXY': <function CC.printXY at 0x0000000001160268>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'CC' objects>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, '__doc__': None, 'setXY': <function CC.setXY at 0x00000000011601E0>}#赋值后没变
del CC
#ee=CC() NameError: name 'CC' is not defined
dd.printXY() # 4 5
第一点是那个self的作用,第二点是为赋值后撒类对象变化了而类却没变
python
中一切皆对象,class
is also a type of object,As shown above, when you instantiate
CC
以后,内存中就有了两个对象(绿色字是对象内部的属性和方法),一个是CC
,一个是dd
,When you execute
dd.setXY(4,5)
时,self
就被设置为dd
,因为setXY
不存在于dd
中,所以解释器沿着父类往上找,在CC
中找到了setXY
并执行,self
,即dd
内部就多了两个成员x
和y
,How does the interpreter know
dd
的父类是CC
呢?答案是,
dd.__class__
When you delete
CC
以后,其实你只是删除了CC
这个变量而已,,并没有删除类CC
所占有的内存,因为dd
还依旧存在的,dd
还通过属性__class__
引用着类CC
(python
Memory management is based on reference counting)So it just can't be found via the variable
CC
找到类而已,但是你可以通过dd.__class__
,So, you can write like this,
ee = dd.__class__()