我是 Python 新手,我需要一些幫助來理解私有方法。我正在做一項(xiàng)任務(wù),我必須輸出寵物的類型、名稱和年齡。我的程序正在運(yùn)行,但我似乎被困在如何將數(shù)據(jù)屬性設(shè)為私有的問題上。這是我的代碼。import random class pet :#how the pets attributes will be displayeddef __init__(animal, type, name, age): animal.type = type animal.name = name animal.age = age #empty list for adding tricks animal.tricks = []#number of fleas are random from 0 to 10fleaCount = random.randint(0,10) def addTrick(animal, trick): animal.tricks.append(trick) def petAge(animal): return animal.age def printInfo(animal): print(f"Pet type : {animal.type} \nPet name : {animal.name}\nPet age : {animal.age}\nPet fleas : {animal.fleaCount}") print("Tricks :") for i in range(len(animal.tricks)): print("",animal.tricks[i])# main program#dog1 informationdog1 = pet("Dog","Max",10) dog1.addTrick("Stay and Bark") dog1.printInfo() #dog2 informationdog2 = pet("Dog","Lily",8)dog2.addTrick("Play Dead and Fetch")dog2.printInfo()#cat1 informationcat1 = pet("Cat","Mittens",11)cat1.addTrick("Sit and High Five")cat1.printInfo()
2 回答

當(dāng)年話下
TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
對象中的私有屬性是通過在它前面加上 來定義的__
,因此在您的情況下它將__age
代替age
. 然后解釋器將修改名稱(即無法直接通過 訪問__age
),但如果有人想通過修改后的名稱訪問,他們?nèi)匀豢梢赃@樣做。Python中沒有真正的私有屬性。
另外:python中對象方法的第一個(gè)參數(shù)應(yīng)該總是命名self
(而不是animal
)。

人到中年有點(diǎn)甜
TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
只需在屬性名稱前使用雙下劃線即可,例如:“__type”、“__age”、“__name”。
如果您想了解有關(guān)公共、私有和受保護(hù)的更多信息:https ://www.tutorialsteacher.com/python/private-and-protected-access-modifiers-in-python
添加回答
舉報(bào)
0/150
提交
取消