pm21-dragon/exercises/release/exercise-07/1__classes.ipynb
2024-11-25 08:20:05 +01:00

14 KiB

None <html> <head> </head>

Classes in Python

First, let's consider some data in a plain Python dictionary:

In [ ]:
car1 = {
    'name': 'Fer',
    'worth': 60000,
    'type_': 'convertible',
    'color': 'red'
}
car2 = {
    'name': 'Jump',
    'worth': 10000,
    'type_': 'van',
    'color': 'blue'
}
In [ ]:
car1['name']

Now, let's make a Python class which will hold this same kind of data:

In [ ]:
class Car:
    def __init__(self,name,worth,type_,color):
        self.name = name
        self.worth = worth
        self.type_ = type_
        self.color = color
    def print_car(self):
        print("%s is worth %d and is a %s %s."%(self.name, self.worth, self.color, self.type_))
In [ ]:
car1 = Car("Fer",60000,"convertible","red")

Takeaway message

  • The data in an instances of a class are conceptually very similar to python dicts with a few special features. One of these special features is methods. Another is that you access instance variables with with the x_instance.name syntax instead of x_dict['name'] syntax.

Q1 creating an instance of a class

We have a class defined for vehicles. Create two new vehicles ("instances of the class") with the variable names car1 and car2. Set car1 to be a red convertible worth EUR 60,000.00 with a name of Fer, and car2 to be a blue van named Jump worth EUR 10,000.00.

In [ ]:
class Vehicle:
    def __init__(self, color, worth, name):    
        self.color = color
        self.worth = worth
        self.name = name
    def get_description(self):
        return 'name: {}, worth: {}, color: {}'.format(self.name, self.worth, self.color)
In [ ]:
# YOUR CODE HERE
raise NotImplementedError()
In [ ]:
# This checks if your code works. Do not change it. It should run without error.
assert( car1.get_description()=="name: Fer, worth: 60000, color: red" )
assert( car2.get_description()=="name: Jump, worth: 10000, color: blue" )

Q2 creating a class

Create a class called Pet. The __init__ function should take 3 arguments: self, name, and sound. The name, and sound arguments should be assigned to the instance variables self.name and self.sound.

In [ ]:
# YOUR CODE HERE
raise NotImplementedError()
In [ ]:
# This checks if your code works. Do not change it. It should run without error.
my_pet = Pet('Bob', 'talk')
assert(my_pet.name=='Bob')
assert(my_pet.sound=='talk')

Q3 writing a method

Now, create a new class called NoisyPet. The __init__ function should be like in Pet. (It takes 3 arguments: self, name, and sound. The name, and sound arguments should be assigned to the instance variables self.name and self.sound.)

NoisyPet should have an additional method called make_noise which takes zero additional arguments (of course self is required). The make_noise for a name of "cricket" and sound of "chirp", this method should return a string like "My pet cricket makes a noise like chirp". Thus, you will need to return a string you have created using string formatting.

In [ ]:
# YOUR CODE HERE
raise NotImplementedError()
In [ ]:
# This checks if your code works. Do not change it. It should run without error.
assert(NoisyPet("cricket", "chirp").make_noise()=="My pet cricket makes a noise like chirp")

Q4 using instances 1

Now create a list named my_pets with 5 instances of the NoisyPet class given the following names and noises.

name noise
Fido slobber
Mr. Skinny Legs (silent)
cricket chirp
Adelheid cackle
Bello bark
In [ ]:
# YOUR CODE HERE
raise NotImplementedError()
In [ ]:
# This checks if your code works. Do not change it. It should run without error.
assert(type(my_pets)==list)
assert(len(my_pets)==5)
for my_pet in my_pets:
    assert(isinstance(my_pet,NoisyPet))
    my_pet.make_noise()

Q5 using instances 2

Now create a function list named get_pet_name_length which takes a single argument, which is an instance of the NoisyPet class. It should return the number of letters in the pet's name.

In [ ]:
# YOUR CODE HERE
raise NotImplementedError()
In [ ]:
# This checks if your code works. Do not change it. It should run without error.
assert(get_pet_name_length(NoisyPet("Bello", "bark"))==5)
assert(get_pet_name_length(NoisyPet("cricket", "chirp"))==7)
</html>