首页 > 代码库 > Python Special Syntax 5:对象相关

Python Special Syntax 5:对象相关

__init__方法一样,还有一个特殊的方法__del__,它在对象消逝的时候被调用。但是很难保证这个方法究竟在 什么时候 运行。如果你想要指明它的运行,你就得使用del语句,

#-*-coding:utf-8class Person:    __privateName=None;#私有变量    count=0;#既可以被实例对象引用,也可以被当做静态对象引用,NND,好混乱。    def __init__(self,name):        self.count+=1        Person.count+=2        print(%s has been created % name)        self.__privateName=name;        self.name=name    def printPrivateName(self):        print(Private Name: %s %  self.__privateName)    def printName(self):        print(Name is %s % self.name)zili=Person(zili)Person.__privateName=zhangsanprint(Person.__privateName)zili.__privateName=zhangsanprint(jiangyao shuchu :%s % zili.__privateName)zili.printName()zili.printPrivateName()print(zili.count)print(Person.count)Person.ABC=abcvalueprint(Person.ABC)

Output:

zili has been created
zhangsan
jiangyao shuchu :zhangsan
Name is zili
Private Name: zili
1
2
abcvalue