Reputation: 47
I'm new to Python, and I need some help understanding private methods. I'm working on an assignment where I have to output the type of pet it is, its name, and age. I have the program working but I seem to be stuck on how I would go about making the data attributes private. This is my code.
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()
Upvotes: 1
Views: 855
Reputation: 768
Just use double underscore before the attribute name, for example: "__type", "__age", "__name".
If you want to learn more about public, private and protected: https://www.tutorialsteacher.com/python/private-and-protected-access-modifiers-in-python
Upvotes: 1
Reputation: 52802
Private properties in an object is defined by prepending it with __
, so in your case it would be __age
instead of age
. The interpreter will then mangle the name (i.e. it would not be accessible directly through __age
), but if someone wanted to get access through the mangled name, they could still do it. There is no such thing as a real private property in Python.
Also: the first parameter to an objects method in python should always be named self
(and not animal
).
Upvotes: 1