Python私人屬性set 和get方法

來源:互聯網
上載者:User

標籤:其他   實現   get   資料   取值   ini   self   建構函式   構造   

class Person(object):
#self不是關鍵字,換成其他的標識符也是可以的,但是一般不要改
def run(self):
print("run")
def eat(self,food):
print("eat" + food)
def say(self):
print("hello! my name is %s,i am %d years old" %(self.name,self.age))
def __init__(self,name,age,height,weight,money):#建構函式;
#定義屬性
self.name = name
self.__age__ = age
self._height = height
self.weight = weight
self.__money = money#不被外部直接存取;相當於_Person__money
#通過內部的方法,去修改私人屬性
#通過自訂的方法實現對私人屬性的賦值與取值
def setMoney(self,money):#對私人屬性的賦值
#資料過濾
if money < 0:
monry = 0
self.__money = money
def getMoney(self):#對私人屬性的取值
return self.__money

per = Person("hanmeimei",20,170,68,1000)
per.setMoney(10)
print(per.getMoney())

‘‘‘
如果要讓內部的屬性,不被外部直接存取,在屬性前加兩個底線__,
在Python中如果在屬性前加兩個底線,那麼這個屬性就變成私人屬性
‘‘‘

‘‘‘
不能直接存取per.__money是因為python解譯器把__money變成
per.__money變成了_Person_money去訪問,但是強烈建議不要這麼幹
注意:不同的解譯器可能存在解釋的變數不一致。
可以這麼訪問對象名._類名__私人屬性 = 新值
per.__money
‘‘‘

#注意:在Python中__xx__這樣的屬性不是私人屬性,這叫特殊變數;特殊變數的值可以直接存取
print(per.__age__)

#在Python中 _xx變數,這樣的執行個體變數外部也是可以訪問的,
#但是按照約定的規則,當我們看到這樣的變數時,意思是“雖然我可以
#被訪問,但是請把我視為私人變數,不要直接存取我"
print(per._height)

Python私人屬性set 和get方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.