類的特殊方法


```#
# 靜態方法(只是名義上歸類管理,但實際上在今天方法裏無法訪問類或實例中的任何屬性)
class cat(object):
    def __init__(self,name):
        self.name=name

    @staticmethod # 實際上和類沒關係了
    def eat(self):
        print("%s is eating %s "%(self.name,"food"))

c=cat("alex")
c.eat(c) #強行有關係要把實例傳進去(其實就是一個函數)

# 類方法
class cat(object):
    name="alex" # 類變量
    def __init__(self,name):
        self.name=name

    @classmethod # 類方法只能訪問類變量,不能訪問實例變量
    def eat(self):
        print("%s is eating %s "%(self.name,"food"))

c=cat("拉大")
c.eat() #強行有關係要把實例傳進去(其實就是一個函數)

# 屬性方法(把一個方法變成靜態屬性)
class cat(object):
    name="alex" # 類變量
    def __init__(self,name):
        self.name=name
        self.__food=None

    @property # 把一個方法變成靜態屬性
    def eat(self):
        print("%s is eating %s " % (self.name,self.__food))
    @eat.setter #(修改)
    def eat(self,food):
        print("set food is " , food)
        self.__food=food
    @eat.deleter #(刪除)
    def eat(self):
        del self.__food
        print("刪完了")

c=cat("拉大")
c.eat
c.eat="漢堡"
c.eat

del c.eat
c.eat

```#

類的特殊成員方法

doc方法

class cat(object):
'''貓的類'''
pass
c=cat()
print(cat.doc) #輸出類的描述信息(貓的類)
print(c.doc)#輸出類的描述信息(貓的類)

module和class方法

from ttt import opp
pp=opp()
print(pp.module) #輸出類是從哪個模塊導入的
print(pp.class) # 輸出類本身路徑什麼的

call方法

class dog(object):
def init(self,name):
self.name=name
def eat(self):
print("eat all the others!")
def call(self,*args,**kwargs):
print("all for one the",args,kwargs)

d=dog("alex")
d() # 運行call方法
dog("alex")() # 運行call方法
d(name="alex")

dict和str方法

class dog(object):
def init(self,name):
self.name=name
def eat(self):
print("eat all the others!")
def call(self,*args,**kwargs):
print("all for one the",args,kwargs)
def str(self): #返回一個誰的對象
return "[obj:%s]"%self.name

d=dog("alex")
print(d)
print(dog.dict) #打印類裏的所有屬性,不包括實例屬性
print(d.dict) #打印所有實例屬性,不包括類的屬性

變成字典的形式

class Foo(object):
def init(self):
self.data={}

def __getitem__(self, key):
    print('__getitem__', key)
    return self.data.get(key)

def __setitem__(self, key, value):
    print('__setitem__', key, value)
    self.data[key]=value

def __delitem__(self, key):
    print('__delitem__', key) #到這一步其實沒有刪掉,是否刪自己決定

obj = Foo()

result = obj['k1'] # 自動觸發執行 getitem
obj['k2'] = 'alex' # 自動觸發執行 setitem
print(obj["k2"])
#print(obj.data)
#obj
#del obj['k1']#到這一步其實沒有刪掉,是否刪自己決定

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