我是Python新手,需要一些帮助来理解私有方法。我正在做一项作业,我必须输出宠物的类型、名字和年龄。我有工作的程序,但我似乎被困在我将如何着手使数据属性私人。这是我的密码。你知道吗
import random
class pet :
#how the pets attributes will be displayed
def __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 10
fleaCount = 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 information
dog1 = pet("Dog","Max",10)
dog1.addTrick("Stay and Bark")
dog1.printInfo()
#dog2 information
dog2 = pet("Dog","Lily",8)
dog2.addTrick("Play Dead and Fetch")
dog2.printInfo()
#cat1 information
cat1 = pet("Cat","Mittens",11)
cat1.addTrick("Sit and High Five")
cat1.printInfo()
只需在属性名称前使用双下划线,例如:“\uuu type”、“\uu age”、“\uu name”。你知道吗
如果您想了解有关公共、私有和受保护的更多信息:https://www.tutorialsteacher.com/python/private-and-protected-access-modifiers-in-python
对象中的私有属性是通过在它前面加上
__
来定义的,因此在您的例子中,它应该是__age
,而不是age
。然后解释器将损坏名称(即,无法通过__age
直接访问),但如果有人想通过损坏的名称访问,他们仍然可以这样做。Python中没有真正的私有属性。你知道吗另外:python中objects方法的第一个参数应该始终命名为
self
(而不是animal
)。你知道吗相关问题 更多 >
编程相关推荐