例項方法 類成員 類方法 靜態方法的基本Demo

2021-10-10 08:57:04 字數 781 閱讀 5849

class people:	

__country='china'

def __init__(self,name):

self.name=name

def yourname(self):

print("my name is ,my country is ".format(self.name,self.__country))

@classmethod

def getcountry(cls):

return cls.__country

@classmethod

def setcountry(cls,value):

cls.__country=value

@staticmethod

def s_print():

a=4b=6

print("---static method +=".format(a,b,a+b))

print(people.getcountry())

zs=people("zs")

print(zs.getcountry())

people.s_print()

zs.s_print()

people.setcountry("中國")

print(zs.getcountry())

物件可以訪問例項方法、類方法和靜態方法;類可以使用類方法和靜態方法。一般情況下,如果要修改例項成員的值,直接使用例項方法;如果修改類成員值,直接使用類方法;如果是輔助功能,考慮使用靜態方法。

例項方法 靜態方法 類方法

首先新建乙個日期date類,屬性為年,月,日,tomorrow 是例項方法,這個最常見,比較簡單,例項方法的第乙個引數是例項物件self 當我們傳入的年月日是2018 6 4這樣的形式,我們就需要先進行字串處理,在這裡使用了元組的拆包 這是最基本的方式,但是這樣寫會有乙個問題,每次傳參都需要進行字串...

類方法,例項方法,靜態方法

python 中的三種方法,有三種類方法,例項方法,靜態方法,這三種方法都在類中,區別在於呼叫的方式不同。例項物件能的呼叫這三種方法,類只能呼叫類方法和靜態方法。class foo object def init self,name self.name name deford func self 定...

例項方法 類方法 靜態方法

示例方法 第乙個引數為self,必須例項化之後才能呼叫的方法 類方法 使用 classmethod進行裝飾,第乙個引數為cls,可以被類呼叫,也可以被例項呼叫。靜態方法 使用 staticmethod進行裝飾,沒有固定的引數,可以被類呼叫,也可以被例項呼叫,一般可以說跟類和例項沒有關係。classa...