Design a Pet Class in Python

write Python code to create a program that meets the following requirements.

Design a class named Pet, which should have the following fields:

  • name: the name field holds the name of the pet
  • type: the type field holds the type of animal that a pet is. Example values are “Dog”, “Cat”, and “Bird”.
  • age: the age field holds the pet’s age

The Pet class should also have the following methods:

  • setName: The setName method stores a value in the name field.
  • setType: The setType method stores a value in the type field.
  • setAge: The setAge method stores a value in the age field.
  • getName: The getName method returns the value of the name field.
  • getType: The getType method returns the value of the type field.
  • getAge: The getAge method returns the value of the age field.

Once you have designed the class, design a program that creates an object of the class and prompts the user to enter the name, type, and age of their pet. Ths data should be stored in the object. Use the object’s accessor methods to retreive the pet’s name, type, and age and display this data on the screen.

What is your question?

class Pet:
    '''
    Class for creating a pet instance
    Have some default values set
    Using a dict as a container
    '''
    def __init__(self, name='Tom', _type='cat', age=15):
        self.pet = {
            'name': name,
            'type': _type,
            'age': age
        }

    # Method for setting pet name
    def set_name(self, name):
        self.pet['name'] = name 

    # Method for setting pet type
    def set_type(self, _type):
        self.pet['type'] = _type 

    # Method for setting pet age
    def set_age(self, age):
        self.pet['age'] = age 

    # Method for getting pet name
    def get_name(self):
        return self.pet['name']

    # Method for getting pet type
    def get_type(self):
        return self.pet['type']
    
    # Method for getting pet age
    def get_age(self):
        return self.pet['age']

    # Method for getting all pet info at once
    def __iter__(self):
        return iter(self.pet.items())

# Set class instance and set values
pet = Pet()
pet.set_name('Rex')
pet.set_type('dog')
pet.set_age(25)

print()
print('Print a single line at a time')
print(f'Pet Name: {pet.get_name()}')
print(f'Pet Type: {pet.get_type()}')
print(f'Pet Age: {pet.get_age()}')

# Set class instance with default values and print
pet2 = Pet()
print()
print('All info at once')
for info in pet2:
    print(f'{info[0]}: {info[1]}')


    

Output:
Print a single line at a time
Pet Name: Rex
Pet Type: dog
Pet Age: 25

All info at once
name: Tom
type: cat
age: 15
    

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.