私有屬性和私有方法

2021-09-05 12:37:14 字數 1252 閱讀 6575

應用場景及定義方式

應用場景:

在實際開發中,物件的某些屬性或方法可能只希望在物件的內部使用,而不希望在外部被訪問到

私有屬性 就是 物件 不希望公開的 屬性

私有方法 就是 方法 不希望公開的 方法

定義方法

在定義屬性或方法時,在屬性名或者方法名前增加兩個下劃線,定義的就是私有屬性或方法

class women(object):

def __init__(self,name):

self.name = name

self.__age = 18

def __secret(self):

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

lily = women('lily')

#print(lily.age)

lily.__secret()

class date(object):

def __init__(self,year,month,day):

self.year = year

self.month = month

self.day = day

# 例項方法(預設情況下會傳遞物件給echo方法)

def echo(self):

print('%s %s %s' %(self.year,self.month,self.day))

# 預設傳遞類本身給這個方法

@classmethod

def as_string(cls,s):

month,day,year = s.split('/')

d = cls(year,month,day) # d = date(2018,10,10)

return d

@staticmethod

def is_vaild(s):

# 批量將年月日轉換成整型

month,day,year = map(int,s.split('/'))

return 0# d = date(2018,10,10)

# print(d)

# d.echo()

s = '10/10/2018'

print(date.as_string(s))

print(date.is_vaild(s))

d = date(2018,10,10)

print(d.is_vaild('10/10/2018'))

私有屬性和私有方法

應用場景 定義方式 不要問女生的年齡 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 ...

私有屬性和私有方法

classa def init self self.num1 100 self.num2 200def test self print 私有方法 d d self.num1,self.num2 def test self print 父類的公有方法 d self.num2 self.test cla...