類屬性類方法,私有屬性私有方法

2021-09-25 07:35:20 字數 867 閱讀 1547

類屬性類方法

類屬性:使用賦值語句在class關鍵字下定義

類方法:在類內部可以直接訪問雷屬性或者其它類方法

class student(objict):

count = 0

definit(self,name):

self.name = name

student.count += 1

@classmethod

def show_student_count(awda):

print('student number is %d' %(awda.count))

student1 = studnet(『xiao ming』)

student2 =

靜態方法

class cat(object):

@staticmethod

def call():

print(『喵』)

cat.call()

私有屬性私有方法

class women():

definit(self,name):

self.name = name

self.__age = 18

def __secert(self):

print(』%s 的年齡是%d』%(self.name,self.__age))

lily = women(『lily』)

print(lily.name)

print(lily.__age)

lily.__secret()

私有屬性和私有方法

應用場景及定義方式 應用場景 在實際開發中,物件的某些屬性或方法可能只希望在物件的內部使用,而不希望在外部被訪問到 私有屬性 就是 物件 不希望公開的 屬性 私有方法 就是 方法 不希望公開的 方法 定義方法 在定義屬性或方法時,在屬性名或者方法名前增加兩個下劃線,定義的就是私有屬性或方法 clas...

私有屬性和私有方法

應用場景 定義方式 不要問女生的年齡 self.age 18 def secret self print 我的年齡是 d self.age xiaofang women 小芳 私有屬性,外部不能直接訪問 print xiaofang.age 私有方法,外部不能直接呼叫 xiaofang.secret...

私有屬性和私有方法

class student object def init self,name,score 前面帶兩個下劃線表示對變數進行私有化 外部不能隨便的訪問和更改 self.name name self.score score defget grand self print my name is s,my ...