Reputation: 45
I'm new to Python and OOP. I have previously done python in procedural programming style.
I need to write a class named Pet, which should have the following data attributes:
It should contain an __init__
initializer that creates these attributes. It should also have
all the mutator and accessor methods. Write a program that creates an object of the
class and prompts the user to enter the name, type, and age of his pet. At the end of the
program, display the pet’s name, type, and age on the screen. The sample output is
given below.
Enter Pet Name: Lucky
Enter Pet Type: Dog
Enter Pet Age: 5
Pet Lucky is a dog, and it is 5 years old
This is what I have done so far (it doesn't run on my cmd, there is no error code)
class Pet:
def set_name(self, name):
self.__name = name
def set_animal_type(self, animal_type):
self.__animal_type = animal_type
def set_age(self,age):
self.__age = age
def get_name(self):
return self.__name
def get_animal_type(self):
return self.__animal_type
def get_age(self):
return self.__age
name = input("Enter pet name: ")
animal_type = input("Enter pet type: ")
age = input("Enter pet age: ")
p = Pet()
p.set_name(name)
p.set_animal_type(animal_type)
p.set_age(age)
print("Pet %s is a %s ,and it is %s years old." %(p.set_name(), p.set_animal_type(), p.set_age()))
Upvotes: 1
Views: 171
Reputation: 3961
You're calling setter instead of getter Change your print line as follows
print("Pet %s is a %s ,and it is %s years old." %(p.get_name(), p.get_animal_type(), p.get_age()))
Also, add missing init method
def __init__(self, name, animal_type, age):
self.name = name
self.animal_type = animal_type
self.age = age
Upvotes: 2
Reputation: 2569
You should read about class method and espeacilly dunder method, here is what you are asking to do.
class Pet:
def __init__(self, name, animal_type, age):
self.name = name
self.animal_type = animal_type
self.age = age
def __str__(self):
return f"Pet {self.name} is a {self.animal_type} ,and it is {self.age} years old."
def __repr__(self):
return self.__str__
def __setattrib__(self, name, value):
self.__dict__[name] = value
def __getattrib__(self, name):
return self.__dict__[name]
name = input("Enter pet name: ")
animal_type = input("Enter pet type: ")
age = input("Enter pet age: ")
p = Pet(name, animal_type, age)
print(p)
p.name = "new_name"
p.animal_type = "cat"
p.age = "10"
print(p)
Upvotes: 1