不歸路系列:Python入門之旅-一定要注意縮進!?。。ㄍ扑])
因為工作(懶惰),幾年了,斷斷續(xù)續(xù)學(xué)習(xí)又半途而廢了一個又一個技能。試著開始用博客記錄學(xué)習(xí)過程中的問題和解決方式,以便激勵自己和順便萬一幫助了別人呢。
最近面向?qū)ο髮懥藗€Python類,到訪問限制(私有屬性)時竟然報錯,好多天百思不得其姐,沒啥破綻??!代碼如下,可就是報錯?。ê竺嬗袌箦e截圖)
class Person(object): def run(self): print("run") def eat(self,food): print("eat " + food) def say(self): print("My name is %s,I am %d years old" % (self.name,self.age)) # 構(gòu)造函數(shù),創(chuàng)建對象時默認的初始化 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 print("哈嘍!我是%s,我今年%d歲了。目前存款%f" %(self.name,self.age,self.__money)) # 想要內(nèi)部屬性不被直接外部訪問,屬性前加__,就變成了私有屬性private self.__money = 100 # 私有屬性需要定義get、set方法來訪問和賦值 def setMoney(self,money): if(money < 0): self.__money = 0 else: self.__money = money def getMoney(self): return self.__money person = Person("小明", 5, 120, 28,93.1) # 屬性可直接被訪問 person.age = 10 print(person.age) # 私有屬性不可直接被訪問或賦值,因為解釋器把__money變成了_Person__money(可以用這個訪問到私有屬性的money,但是強烈建議不要),以下2行會報錯 # person.money = 10 # print(person.__money) # 可以調(diào)用內(nèi)部方法訪問和賦值 print(person.getMoney()) person.setMoney(-10) print(person.getMoney())
Excuse me?!咋個就沒有,那不上面大大擺著倆內(nèi)部方法嘛!
昨天看著看著突然迸發(fā)了個小火星子,想起來縮進不對了,如圖:
把兩個方法減一個縮進,就算是出來了,是類的方法,和__init__并列了,自然就正確了。
class Person(object): def run(self): print("run") def eat(self,food): print("eat " + food) def say(self): print("My name is %s,I am %d years old" % (self.name,self.age)) # 構(gòu)造函數(shù),創(chuàng)建對象時默認的初始化 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 print("哈嘍!我是%s,我今年%d歲了。目前存款%f" %(self.name,self.age,self.__money)) # 想要內(nèi)部屬性不被直接外部訪問,屬性前加__,就變成了私有屬性private self.__money = 100 # 私有屬性需要定義get、set方法來訪問和賦值 def setMoney(self, money): if (money < 0): self.__money = 0 else: self.__money = money def getMoney(self): return self.__money person = Person("小明", 5, 120, 28,93.1) # 屬性可直接被訪問 person.age = 10 print(person.age) # 私有屬性不可直接被訪問或賦值,因為解釋器把__money變成了_Person__money(可以用這個訪問到私有屬性的money,但是強烈建議不要),以下2行會報錯 # person.money = 10 # print(person.__money) # 可以調(diào)用內(nèi)部方法訪問和賦值 print(person.getMoney()) person.setMoney(-10) print(person.getMoney())
總結(jié)下:一定要細心!細心??!再細心?。?!
注意縮進
注意縮進
注意縮進
以上所述是小編給大家介紹的Python入門一定要注意縮進詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
python光學(xué)仿真通過菲涅耳公式實現(xiàn)波動模型
這篇文章主要介紹了python光學(xué)仿真通過菲涅耳公式實現(xiàn)波動模型的示例解析原理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2021-10-10python2 與python3的print區(qū)別小結(jié)
這篇文章主要介紹了python2 與python3的print區(qū)別小結(jié),需要的朋友可以參考下2018-01-01利用Python中unittest實現(xiàn)簡單的單元測試實例詳解
如果項目復(fù)雜,進行單元測試是保證降低出錯率的好方法,Python提供的unittest可以很方便的實現(xiàn)單元測試,從而可以替換掉繁瑣雜亂的main函數(shù)測試的方法,將測試用例、測試方法進行統(tǒng)一的管理和維護。本文主要介紹了利用Python中unittest實現(xiàn)簡單的單元測試。2017-01-01