pm21-dragon/exercises/source/exercise-07/1__classes.ipynb
2024-11-29 08:39:51 +01:00

12 KiB
Executable file

None <html> <head> </head>

Classes in Python

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

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

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

In [3]:
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 [4]:
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 [5]:
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 [6]:
car1 = Vehicle('red', 60000, 'Fer')
car2 = Vehicle('blue', 10000, 'Jump')
In [7]:
# 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 [8]:
class Pet:
    def __init__(self, name, sound):
        self.name = name
        self.sound = sound
In [9]:
# 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 [10]:
class NoisyPet:
    def __init__(self, name, sound):
        self.name = name
        self.sound = sound
    def make_noise(self):
        return "My pet {} makes a noise like {}".format(self.name, self.sound)
In [11]:
# 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 [12]:
my_pets = [
    NoisyPet("Fido", "slobber"),
    NoisyPet("Mr. Skinny Legs", "(silent)"),
    NoisyPet("cricket", "chirp"),
    NoisyPet("Adelheid", "cackle"),
    NoisyPet("Bello", "bark"),
]
In [13]:
# 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 [14]:
def get_pet_name_length(pet):
    return len(pet.name)
In [15]:
# 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>