Python 元類的簡單應用 建立特定類

2021-09-23 14:06:55 字數 1924 閱讀 1568

在python中元類就是用來建立類的「東西」,python中的類也是物件。

元類就是用來建立這些類(物件)的,元類就是類的類,你可以這樣理解為:

myclass = metaclass() # 使用元類建立出乙個物件,這個物件稱為「類」

my_object = myclass() # 使用「類」來建立出例項物件

建立特定型別的類時可用元類(例如.預設例項屬性為大寫)

#-*- coding:utf-8 -*-

def upper_attr(class_name, class_parents, class_attr):

#遍歷屬性字典,把不是__開頭的屬性名字變為大寫

new_attr = {}

for name,value in class_attr.items():

if not name.startswith("__"):

new_attr[name.upper()] = value

#呼叫type來建立乙個類

return type(class_name, class_parents, new_attr)

class foo(object, metaclass=upper_attr):

bar = 'bip'

print(hasattr(foo, 'bar'))

print(hasattr(foo, 'bar'))

f = foo()

print(f.bar)

#coding=utf-8

class upperattrmetaclass(type):

# __new__ 是在__init__之前被呼叫的特殊方法

# __new__是用來建立物件並返回之的方法

# 而__init__只是用來將傳入的引數初始化給物件

# 你很少用到__new__,除非你希望能夠控制物件的建立

# 這裡,建立的物件是類,我們希望能夠自定義它,所以我們這裡改寫__new__

# 如果你希望的話,你也可以在__init__中做些事情

# 還有一些高階的用法會涉及到改寫__call__特殊方法,但是我們這裡不用

def __new__(cls, class_name, class_parents, class_attr):

# 遍歷屬性字典,把不是__開頭的屬性名字變為大寫

new_attr = {}

for name, value in class_attr.items():

if not name.startswith("__"):

new_attr[name.upper()] = value

# 方法1:通過'type'來做類物件的建立

return type(class_name, class_parents, new_attr)

# 方法2:復用type.__new__方法

# 這就是基本的oop程式設計,沒什麼魔法

# return type.__new__(cls, class_name, class_parents, new_attr)

# python3的用法

class foo(object, metaclass=upperattrmetaclass):

bar = 'bip'

# python2的用法

# class foo(object):# __metaclass__ = upperattrmetaclass

# bar = 'bip'

print(hasattr(foo, 'bar'))

# 輸出: false

print(hasattr(foo, 'bar'))

# 輸出:true

f = foo()

print(f.bar)

# 輸出:'bip'

注:

Python程式設計 元類的簡單使用

python 2.7.5 舊式類 class foo pass foo foo print type foo print type foo print type type python 3.6.5 新式類 class foo pass foo foo print type foo print typ...

python元類的使用 Python的元類如何使用

這次給大家帶來python的元類如何使用,使用python元類的注意事項有哪些,下面就是實戰案例,一起來看一下。今天我的任務就是徹底明白什麼是元類,一起看看。要搞懂元類,我們還是先從物件說起。python 一切皆物件,這句話你一定有聽說過 現在你就聽說了 乙個數字是物件,乙個字串是物件,乙個列表是物...

Python 乙個簡單的類的建立和應用

1 建立類,設定屬性和給屬性設定預設值,設定方法並訪問類的屬性 2 利用類建立多個例項,以及呼叫類的方法的兩種辦法 3 設定更新屬性的函式,並更新例項的屬性。1 class dog object 2 建立小狗類 3 4def init self,name,age 5 初始化引數,python建立例項...