這篇文章主要介紹了Python入門一定要注意縮進,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧
因爲工作(懶惰),幾年了,斷斷續續學習又半途而廢了一個又一個技能。試着開始用博客記錄學習過程中的問題和解決方式,以便激勵自己和順便萬一幫助了別人呢。
最近面向對象寫了個Python類,到訪問限制(私有屬性)時竟然報錯,好多天百思不得其姐,沒啥破綻啊!代碼如下,可就是報錯!(後面有報錯截圖)
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)) # 構造函數,創建對象時默認的初始化 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)) # 想要內部屬性不被直接外部訪問,屬性前加__,就變成了私有屬性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) # 可以調用內部方法訪問和賦值 print(person.getMoney()) person.setMoney(-10) print(person.getMoney())
Excuse me?!咋個就沒有,那不上面大大擺着倆內部方法嘛!
昨天看着看着突然迸發了個小火星子,想起來縮進不對了,如圖:
把兩個方法減一個縮進,就算是出來了,是類的方法,和__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)) # 構造函數,創建對象時默認的初始化 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)) # 想要內部屬性不被直接外部訪問,屬性前加__,就變成了私有屬性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) # 可以調用內部方法訪問和賦值 print(person.getMoney()) person.setMoney(-10) print(person.getMoney())
總結下:一定要細心!細心!!再細心!!!
注意縮進
注意縮進
注意縮進
以上所述是小編給大家介紹的Python入門一定要注意縮進詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對神馬文庫網站的支持!