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

在網站設計、成都做網站中從網站色彩、結構布局、欄目設置、關鍵詞群組等細微處著手,突出企業(yè)的產品/服務/品牌,幫助企業(yè)鎖定精準用戶,提高在線咨詢和轉化,使成都網站營銷成為有效果、有回報的無錫營銷推廣。創(chuàng)新互聯專業(yè)成都網站建設10年了,客戶滿意度97.8%,歡迎成都創(chuàng)新互聯客戶聯系。
**classmethod(function)** #where function is an name of function
classmethod()參數:
classmethod()函數只接受一個參數
| 參數 | 描述 | 必需/可選 |
|---|---|---|
| 函數 | 要轉換為類方法的函數 | 需要 |
classmethod()返回值
方法的返回值或輸出是類方法,可以在沒有類實例的情況下調用。
| 投入 | 返回值 | | 功能 | 返回傳遞函數的類方法 |
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)新互聯Python教程:Pythonclassmethod()
標題路徑:http://m.fisionsoft.com.cn/article/cdhheep.html


咨詢
建站咨詢
