如何在python中使数据属性私有化

2024-05-19 02:53:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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()

Tags: nameagedeftyperandomprintpettricks
2条回答

只需在属性名称前使用双下划线,例如:“\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)。你知道吗

相关问题 更多 >

    热门问题