Python元類 & type動態創建類 & 類裝飾器

元類

類也是對象(屬於元類的對象)

      #打印字符串(字符串是對象)
      print("HelloWorld")  
     #打印類名,類同樣爲一個對象
     print(Person)

 

使用type可以動態創建類

     type(類名,由父類名稱組成的元組(可以爲空),包含屬性的字典(名稱和值))

#案例1:使用type創建類
Myclass = type("MyClass3",(),{})
m1 = Myclass()
print(type(m1))


 

#案例2:使用type創建帶有屬性(方法)的類
def show(self):
	print("---num---%d"%self.num)

# 使用元類(type)創建類
Test = type("Test",(),{"show":show})
t = Test()
t.num = 100
t.show()

#案例3:使用type動態創建一個繼承指定類的類
class Animal():
	def __init__(self,color="Yellow"):
		self.color = color
	def eat(self):
		print("吃死你")
		
Dog = type("Dog",(Animal,),{})
dog = Dog()
dog.eat()
print(dog.color)

 

類裝飾器

和函數裝飾器類似,只不過你在返回func的時候顯示對象不能被調用,重寫__call__()方法後,對象可以直接進行調用

Test 等價於 test = Test(test) 裝飾器特性

Test(test)的這個test就是func

class Test(object):
	def __init__(self,func):
		print("--初始化--")
		print("func name is %s"%func.__name__)
		self.__func = func
	# 重寫該方法後,對象可以直接進行調用
	def __call__(self):
		print("--裝飾器中的功能--")
		self.__func()
	
# @Test 等價於 test = Test(test) 裝飾器特性
@Test
def test():
	print('--test 函數---')
	# 本身test指向函數test,但是裝飾器將test指向了對象。
	# 對象本身不可以被調用,但是重寫__call__方法之後則會被調用
test()

 

注意類裝飾器的形式是非主流的形式,以後要加功能就寫閉包

當別人寫了類裝飾器你認得就可以了

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章