python 類屬性,靜態呼叫,變數私有化

2021-10-02 17:59:45 字數 1081 閱讀 9056

類屬性:

class toy(object):

count = 0

def __init__(self,name):

self.name=name

toy.count +=1

@classmethod

def toy_count(cls):

print('玩具的數量 %d' %(cls.count))

toy1 = toy('樂高')

toy2 = toy('泰迪熊')

toy.toy_count()

結果:玩具的數量 2

靜態呼叫:

class cat(object):

@staticmethod

def call():

print('喵喵')

cat.call() #不需要建立物件可以直接呼叫方法(類名。方法名)

結果:喵喵

變數私有化

class student(object):

def __init__(self,name,score):

self.__name =name #變數前面加上兩個下劃線表示對變數進行私有化,不能隨意訪問和更改

self.__score =score

def get_grand(self): #私有化後可以在類中設定方法,通過方法去呼叫

print('name is %s ,grand is %d ' %(self.__name,self.__score))

def get_name(self):

print(self.__name)

def get_score(self):

print(self.__score)

tom = student('tom',90)

#print(tom.name) #私有變數無法檢視,會報錯

#print(tom.score)

tom.get_name() #通過方法呼叫檢視

tom.get_score()

結果:tom

90

python 類屬性,靜態呼叫,變數私有化

類屬性 class toy object count 0 def init self,name self.name name toy.count 1 classmethod def toy count cls print 玩具的數量 d cls.count toy1 toy 樂高 toy2 toy ...

python 類屬性 用處 Python類屬性詳解

類屬性1.類定義後就存在,而且不需要例項化 2.類屬性使得相同類的不同例項共同持有相同變數 類屬性例項 attrb.py class testcss cssa class attribe def init self self.a 0 self.b 10 def info self print a s...

Python 類屬性 類方法 靜態方法

一.類屬性 1.參考 一 參考 二 說明 1.類屬性可以使用類物件或例項物件訪問 2.可以通過類物件來修改類屬性,但是不可以通過例項物件來修改類屬性。class house 類屬性 price high 通過類物件獲取類屬性值 print house.price 通過例項物件獲取類屬性值 h hou...