不歸路系列:Python入門之旅-一定要注意縮進!?。。ㄍ扑])
因為工作(懶惰),幾年了,斷斷續(xù)續(xù)學習又半途而廢了一個又一個技能。試著開始用博客記錄學習過程中的問題和解決方式,以便激勵自己和順便萬一幫助了別人呢。
最近面向?qū)ο髮懥藗€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))
# 構(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é)下:一定要細心!細心!!再細心!?。?/p>
注意縮進
注意縮進
注意縮進
以上所述是小編給大家介紹的Python入門一定要注意縮進詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Python中使用aiohttp模擬服務器出現(xiàn)錯誤問題及解決方法
這篇文章主要介紹了Python中使用aiohttp模擬服務器出現(xiàn)錯誤,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10

