python 詳解類class的方法:執行個體方法、類方法、靜態方法(三)__python

來源:互聯網
上載者:User

1、執行個體方法 執行個體方法的第一個參數必須是”self”,執行個體方法只能通過類執行個體進行調用,這時候“self”就代表這個類執行個體本身。通過”self”可以直接存取執行個體的屬性。

class person(object):    tall = 180    hobbies = []    def __init__(self, name, age,weight):        self.name = name        self.age = age        self.weight = weight    def infoma(self):        print('%s is %s weights %s'%(self.name,self.age,self.weight))Bruce = person("Bruce", 25,180)Bruce.infoma()

Bruce is 25 weights 180


2、類方法 類方法以cls作為第一個參數,cls表示類本身,定義時使用@classmethod裝飾器。通過cls可以訪問類的相關屬性。

class person(object):    tall = 180    hobbies = []    def __init__(self, name, age,weight):        self.name = name        self.age = age        self.weight = weight    @classmethod     #類的裝飾器    def infoma(cls):   #cls表示類本身,使用類參數cls        print(cls.__name__)        print(dir(cls))#cls表示類本身person.infoma()  # 直接調用類的裝飾器函數,通過cls可以訪問類的相關屬性Bruce = person("Bruce", 25,180)   #也可以通過兩步驟來實現,第一步執行個體化person,第二步調用裝飾器Bruce.infoma() 

person['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'hobbies', 'infoma', 'tall']

person['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'hobbies', 'infoma', 'tall']

3、靜態方法 與執行個體方法和類方法不同,靜態方法沒有參數限制,既不需要執行個體參數,也不需要類參數,定義的時候使用@staticmethod裝飾器。 同類方法一樣,靜態法可以通過類名訪問,也可以通過執行個體訪問。

class person(object):    tall = 180    hobbies = []    def __init__(self, name, age,weight):        self.name = name        self.age = age        self.weight = weight    @staticmethod    #靜態方法裝飾器    def infoma():     #沒有參數限制,既不要執行個體參數,也不用類參數        print(person.tall)        print(person.hobbies)#person.infoma()   #靜態法可以通過類名訪問Bruce = person("Bruce", 25,180)   #通過執行個體訪問Bruce.infoma() 

靜態方法、類方法使用區別或者說使用情境

1、類方法用在類比java定義多個建構函式的情況。
由於python類中只能有一個初始化方法,不能按照不同的情況初始化類。
參考django https://docs.djangoproject.com/en/1.9/ref/models/instances/
請看下面的代碼。

# coding:utf-8class Book(object):    def __init__(self, title):        self.title = title    @classmethod    def create(cls, title):        book = cls(title=title)        return bookbook1 = Book("python")book2 = Book.create("python and django")print(book1.title)print(book2.title)
特別說明,靜態方法也可以實現上面功能,當靜態方法每次都要寫上類的名字,不方便。

2、類中靜態方法方法調用靜態方法的情況。
下面的代碼,靜態方法調用另一個靜態方法,如果改用類方法調用靜態方法,可以讓cls代替類,

讓代碼看起來精簡一些。也防止類名修改了,不用在類定義中修改原來的類名。

# coding:utf-8class Foo(object):    X = 1    Y = 2    @staticmethod    def averag(*mixes):        return sum(mixes) / len(mixes)    @staticmethod    def static_method():        return Foo.averag(Foo.X, Foo.Y)    @classmethod    def class_method(cls):        return cls.averag(cls.X, cls.Y)foo = Foo()print(foo.static_method())print(foo.class_method())

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.