1. 程式人生 > >原來Python類還有這麽多花樣

原來Python類還有這麽多花樣

urn 分享 方式 return python val UNC 繼承類 技術分享

"""metaclass的作用是指定當前類由誰來創建"""


# 第一種創建類的方式
class Foo(object):
name = "小強" # 類的靜態字段

def func(self):
return 666


val = Foo()
print(val.name)

# 第二種創建類的方式
Foo1 = type("Foo", (object,), {"name": "小強", "func": lambda self: 666})

val1 = Foo1()
print(val1.name)


# 2.自定義type
class YouType(type):
pass


class Foo2(object, metaclass=YouType): # metaclass指定當前繼承類
name = "小老鼠"

def func(self):
return "貓不抓"


val2 = Foo2()
print(val2.name)

Foo3 = YouType("Foo", (object,), {"name": "小老鼠", "func": lambda self: "貓不抓"})

val3 = Foo3()
print(val3.name)


# 3.metaclass
class MyType(type):

def __init__(self, *args, **kwargs):
super(MyType, self).__init__(*args, **kwargs)

def __call__(cls, *args, **kwargs):
obj = cls.__new__(cls)
cls.__init__(obj, *args, **kwargs)
return obj


class Foo4(object, metaclass=MyType):
name = "旺財"

def __init__(self):
pass

def __new__(cls, *args, **kwargs):
return object.__new__(cls)

def func(self):
return 666


# Foo4是MyType的一個對象
obj = Foo4()
print(obj.name)

技術分享圖片

原來Python類還有這麽多花樣