這篇文章主要介紹了python用類方法,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。

在Python中類方法(class method)采用裝飾器@classmethod來定義。
我們直接看例子。
class Kls(object):
num_inst = 0
def __init__(self):
Kls.num_inst = Kls.num_inst + 1
@classmethod
def get_no_of_instance(cls):
return cls.num_inst
ik1 = Kls()
ik2 = Kls()
print ik1.get_no_of_instance()
print Kls.get_no_of_instance()類方法用在模擬java定義多個構(gòu)造函數(shù)的情況。
由于python類中只能有一個初始化方法,不能按照不同的情況初始化類。
coding:utf-8
class Book(object):
def __init__(self, title):
self.title = title
@classmethod
def class_method_create(cls, title):
book = cls(title=title)
return book
@staticmethod
def static_method_create(title):
book= Book(title)
return book
book1 = Book("use instance_method_create book instance")
book2 = Book.class_method_create("use class_method_create book instance")
book3 = Book.static_method_create("use static_method_create book instance")
print(book1.title)
print(book2.title)
print(book3.title)感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享python用類方法內(nèi)容對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,遇到問題就找創(chuàng)新互聯(lián),詳細(xì)的解決方法等著你來學(xué)習(xí)!
本文標(biāo)題:python用類方法-創(chuàng)新互聯(lián)
當(dāng)前鏈接:http://www.chinadenli.net/article38/dcccsp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、微信公眾號、域名注冊、營銷型網(wǎng)站建設(shè)、Google、商城網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)