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----

五、__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__
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章