新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Pythonclassmethod()
通常要調(diào)用一個類的方法,我們需要首先創(chuàng)建該類的一個實例或?qū)ο?。但是類方法綁定到類,而不是它的對象,所以類方法函?shù)的創(chuàng)建返回給定函數(shù)的類方法

在網(wǎng)站設(shè)計、成都做網(wǎng)站中從網(wǎng)站色彩、結(jié)構(gòu)布局、欄目設(shè)置、關(guān)鍵詞群組等細微處著手,突出企業(yè)的產(chǎn)品/服務(wù)/品牌,幫助企業(yè)鎖定精準用戶,提高在線咨詢和轉(zhuǎn)化,使成都網(wǎng)站營銷成為有效果、有回報的無錫營銷推廣。創(chuàng)新互聯(lián)專業(yè)成都網(wǎng)站建設(shè)10年了,客戶滿意度97.8%,歡迎成都創(chuàng)新互聯(lián)客戶聯(lián)系。
**classmethod(function)** #where function is an name of function
classmethod()參數(shù):
classmethod()函數(shù)只接受一個參數(shù)
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 函數(shù) | 要轉(zhuǎn)換為類方法的函數(shù) | 需要 |
classmethod()返回值
方法的返回值或輸出是類方法,可以在沒有類實例的情況下調(diào)用。
| 投入 | 返回值 | | 功能 | 返回傳遞函數(shù)的類方法 |
Python 中classmethod()方法的示例
示例 1:如何創(chuàng)建類方法?
class Products:
getcode = ‘P36’
def getProductCode(cls):
print('The Product Code is:', cls.getcode)
# create printCode class method
Products.getProductCode = classmethod(Products .getProductCode )
Products.getProductCode ()
輸出:
The Product Code is: P36 示例 2:如何使用類方法創(chuàng)建工廠方法?
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
pers 19)
person.display()
pers 1985)
person1.display()
輸出:
Adam's age is: 19
John's age is: 31 示例 3:類方法如何用于繼承?
from datetime import date
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
def fromFathersAge(name, fatherAge, fatherPersonAgeDiff):
return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
class Man(Person):
sex = 'Male'
man = Man.fromBirthYear('John', 1985)
print(isinstance(man, Man))
man1 = Man.fromFathersAge('John', 1965, 20)
print(isinstance(man1, Man))
輸出:
True
False 當前文章:創(chuàng)新互聯(lián)Python教程:Pythonclassmethod()
轉(zhuǎn)載來于:http://www.5511xx.com/article/cdhheep.html


咨詢
建站咨詢
