一、__del__(self): 对象消失的时候调用此方法。
>>> class cat(object):
def __del__(self):
print("对象消失")
>>> import sys
>>> cat1=cat() #创建一个cat1
>>> sys.getrefcount(cat1) #测试对象的引用个数,比实际大1,此时为2
2
>>> cat2=cat1 #又创建了一个引用,此时为3
>>> sys.getrefcount(cat1)
3
>>> sys.getrefcount(cat2)
3
>>> del cat1 #删除了一个引用,cat1 不在指向对象,cat2还指向对象,此时引用个数为2
>>> sys.getrefcount(cat2)
2
>>> del cat2 #又删除了一个,此时没有引用指向对象,对象消失,调用__del__()方法
对象消失
二、类方法 @classmethod
>>> class test(object):
def show(self):
print("This is a class")
@classmethod #定义类方法
def way(cls):
print("This is a class method")
>>> a=test()
>>> a.way() #用对象调用类方法
This is a class method
>>> test.way() #用类调用类方法
This is a class method
三、静态方法:@staticmethod ,一般用于既和类没关系也和对象没关系的使用
>>> class test(object):
def show(self):
print("This is a class")
@staticmethod #定义静态方法
def way( ): #可以没有参数
print("This is a static method")
>>> a=test()
>>> a.way() #对象调用
This is a static method
>>> test.way() #类调用
This is a static method
四、__new__( )方法:静态方法,用于创建对象,__init__( )用于对象的初始化
>>> class test(object):
def show(self):
print("This is show function")
>>> a=test() #调用__new__()方法来创建对象,然后用一个变量来接收__new__()方法的返回值,这个返回值是创建出来对象的引用。调用__init__()方法来初始化对象。
子类中重写__new__( )方法,要调用父类__new__( )方法,要返回对象的引用,对象才能被创建。
重写__new__( )方法,可以创建单例
<一>没返回,没调用父类__new__()方法
>>> class shit(object):
def show(self):
print("-----show----")
def __new__(cls):
print("重写new方法")
>>> a=shit()
重写new方法
>>> a.show() #没有调用父类__new__(cls)方法,报错
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
a.show()
AttributeError: 'NoneType' object has no attribute 'show'
<二> 调用父类的__new__(cls)方法,没有返回
class shit(object):
def show(self):
print("-----show----")
def __new__(cls):
print("重写new方法")
object.__new__(cls)
>>> a=shit()
重写new方法
>>> a.show()
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
a.show()
AttributeError: 'NoneType' object has no attribute 'show'
<三> 有返回,调用父类__new__()方法
>>> class shit(object):
def show(self):
print("-----show----")
def __new__(cls):
print("重写new方法")
return object.__new__(cls) #调用父类的__new__(cls)方法
>>> a=shit()
重写new方法
>>> a.show()
-----show----
五、__slots__方法:限制对象动态添加属性和方法
>>> class student(object):
__slots__=["name","age"] #添加限制
def __init__(self,stuName,stuAge):
self.name=stuName
self.age=stuAge
>>> student.Persons=100 #对类没有限制
>>> stu1=student("ma dongmei",17)
>>> stu1.gender="girl"
#不可以为对象添加属性,报错
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
stu1.gender="girl"
AttributeError: 'student' object has no attribute 'gender'
对于__slot__有以下几个需要注意的地方:
- __slots__只对对象进行限制,不对类进行限制
- __slots__不仅限制类对象的属性,还限制类对象的方法
- __slots__仅对当前类起作用,对继承的子类不起作用
- 在子类中定义__slots__,子类允许定义的属性就是自身的__slots__加上父类的__slots__