首先介紹幾個概念:
1、#所謂的靜态方法就是這個方法任何類都可以調用,程式一加載就存在的方法
2、所謂的類方法就是這個類一加載就存在的方法,不用執行個體化這個類就已經存在的方法
3、所謂的元類就是建立類的類
元類: type
type
我們知道對象是通過構造函數來初始化的,name對象到底是誰建立的呢。其實我們再之前就接觸過元類。例如我們建立整形類用int,建立字元串類用str,那麼我們建立對象類使用什麼來建立的。這裡我們就提到了type這個元類。
type
是建立類的元類,就像認識形态領域的元認知是對認知的認知。
type
舉例:
@staticmethod
def run():
print("runing.......")
def eat(self,food):
print("eat......."+food)
@classmethod
def smile(cls):
print("smile.........")
def createObvject():
p1 = type("Person", (), {"name": "hongbiao", "age": , "run": run,"eat": eat,"smile":smile})
return p1
if __name__ == '__main__':
per = createObvject()
per.smile()
person = per()
print(person.name)
print(person.age)
print(hasattr(per, "name"))
person.run()
person.eat("hhh")
person.smile()
列印結果
smile.........
hongbiao
25
True
runing.......
eat.......hhh
smile.........
從上面我們可以得到 type
這個就是元類,通過這個原來來建立對象, createObvject
裡面封裝了type,傳回一個對象,注意是傳回一個對象而不是執行個體對象。 per()
表示執行個體化一個對象。
type
createObvject
per()
分析type這個方法:
源碼如下:
def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__
"""
type(object_or_name, bases, dict)
type(object) -> the object's type
type(name, bases, dict) -> a new type
# (copied from class doc)
"""
pass
type接收三個參數,分别是對象名稱,繼承内容也就是一般類後面的括号,第三個參數是一個字典類型,用來存貯屬性。
這裡的屬性分為一般屬性,靜态屬性,和類屬性
靜态屬性需要使用裝飾器
staticmethod
修飾,而類屬性需要用
classmethod
來修飾
python動态添加方法
python 作為一門動态的語言,可以在代碼執行的過程中來添加方法
def run(self):
print("running..........")
import types
class Person(object):
def __init__(self, name=None,age=None):
this.name = name
this.age = age
def eat(self):
print("eat...........")
p = Person("hb", )
p.eat()#正常
p.run()#報錯,因為run并不是Person的方法
# 那麼我們想添加進去,怎麼弄呢
import types
p.run = types.MethodType(run,p)
# 執行完上面的代碼之後下面再調用這個方法就不會報錯了
p.run()
# 列印結果:"running.........."