python基础之类中常见内置方法

一、__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----

猜你喜欢

转载自blog.csdn.net/Panda996/article/details/84791609