Module 7 - Section 1 - Classes

Site: ΕΛ/ΛΑΚ Moodle
Course: Python Lab
Book: Module 7 - Section 1 - Classes
Printed by: Guest user
Date: Sunday, 12 May 2024, 10:05 PM

Description

After the completion of this module the students will be able to:

  • identify a class inside Python code
  • present the necessary parts for constructing a class
  • create code to construct a simple class
  • create and use methods in a class
  • distinguish the references from the objects of a class
  • rewrite the classes code to implement constructors

7.1.1 - What is a Class

Classes and objects are very powerful programming tools. They make programming easier. 

Objects have attributes, such as a person's name, height, and age. Objects also have methods. Methods define what an object can do, like run, jump, or sit.

A Class is a structure that has all the information needed to define all the characteristics of an object.

shawn the sheep

In the above image Animal is a Class and Dog and Sheep are Animal Class Objects.

The Animal Class has attributes (characteristics) of the animals, like color, number of legs, weight, speed, etc.

7.1.2 - Create a Class

To create a Class we can define it, in the same way as a function. Class names always start with a capital letter unlike functions. While it is possible to begin a class with a lower case letter, it is not considered good practice.

Copy the above code to Thonny's Script Area and save it as animals in your projects folder.

class Animal(): """ This is a class that represents animals in a game. """ def __init__(self): """ Set up the animals fields. """ self.name = "" self.type = "" self.color = "" self.legs = "" self.speed = ""

In the code above, Animal is the class name. The variables in the class, such as name, type, color, legs and speed are called attributes or fields.

The def __init__(self)  is a special function called a constructor that is run automatically when the class is created.

The self. is kind of like the pronoun my. When inside the class Animal we are talking about my name, my type, my color, etc.

Inside the Script Area of Thonny add the following code after line 10 taking care of indentation.

# Create an animal shawn = Animal() #shawn's attributes shawn.name="Shawn" shawn.type="sheep" shawn.color="white" shawn.legs=4 shawn.speed=50 # Create another animal kitty = Animal() #kitty's attributes kitty.name="Kitty" kitty.type="cat" kitty.color="orange" kitty.legs=4 kitty.speed=24

With the above code, after creating the class Animal, we have created two instances of class animals, a sheep and a cat. Those two instances are called objects. A simple definition is that an object it is an instance of a class.

To visualize the execution of this code click here (www.pythontutor.com) 

animals class

class

7.1.3 - Class methods

In addition to attributes, classes may have methods. A method is a function that exists inside of a class. Changing the earlier example we create a class of a Dog and add a method for a dog bark. Copy the code below to the script area of Thonny, save it as dogClass and run it.

class Dog(): def __init__(self): self.age = 0 self.name = "" self.weight = 0 def bark(self): print("Woof")


In the above code the method definition is a function inside the class. The big difference is the addition of the parameter self inside the definition parenthesis. This parameter is required even if the function does not use it.

Here are the important items to keep in mind when creating methods for classes:

  • Attributes should be listed first, methods after.
  • The first parameter of any method must be self.
  • Method definitions are indented exactly one tab stop.

Methods may be called in a manner similar to referencing attributes from an object. Write the following commands in CLI area of Thonny.

>>> my_dog = Dog()

>>> my_dog.name = "Jack"

>>> my_dog.weight = 14

>>> my_dog.age = 5

>>> my_dog.bark()

Now change the function inside the script to: 

def bark(self): print("Woof says", self.name)
save it, run it and write the following commands to CLI area.


>>>  my_dog = Dog()

>>>  my_dog.name = "Jack"

>>>  my_dog.bark()



7.1.4 - A Ball class

This example code could be used in Python/Pygame to draw a ball. Having all the parameters contained in a class makes data management easier.

class Ball(): def __init__(self): # --- Class Attributes --- # Ball position self.x = 0 self.y = 0 # Ball's vector self.change_x = 0 self.change_y = 0 # Ball size self.size = 10 # Ball color self.color = [255,255,255] # --- Class Methods --- def move(self): self.x += self.change_x self.y += self.change_y def draw(self, screen): pygame.draw.circle(screen, self.color, [self.x, self.y], self.size )

Below is the code that would go ahead of the main program loop to create a ball and set its attributes:
theBall = Ball() theBall.x = 100 theBall.y = 100 theBall.change_x = 2 theBall.change_y = 1 theBall.color = [255,0,0]

This code would go inside the main loop to move and draw the ball:

theBall.move() theBall.draw(screen)

The complete code can be downloaded from here

7.1.5 - References

Take a look at the following code.

class Person(): def __init__(self): self.name = "" self.money = 0 bob = Person() bob.name = "Bob" bob.money = 100 nancy = Person() nancy.name = "Nancy" print(bob.name, "has", bob.money, "euros.") print(nancy.name, "has", nancy.money, "dollars.")


To visualize click on the link to transfer to http://www.pythontutor.com

The code above has nothing new. But the code below has a diffrence:

class Person(): def __init__(self): self.name = "" self.money = 0 bob = Person() bob.name = "Bob" bob.money = 100 nancy = bob nancy.name = "Nancy" print(bob.name, "has", bob.money, "euros.") print(nancy.name, "has", nancy.money, "euros.")


To visualize click on the link to transfer to http://www.pythontutor.com

The difference in pythontutor is in line 10. nancy is a reference to bob. Besides reference, we can call this address, pointer, or handle. A reference is an address in computer memory for where the object is stored. This address is a hexadecimal number which, if printed out, might look something like 0x1e504. When the code  is executed, the address is copied rather than the entire object the address points to.

reference address

7.1.6 - Functions and References

Now let's use the reference with a function.

def give_money(person): person.money += 100 class Person(): def __init__(self): self.name = "" self.money = 0 bob = Person() bob.name = "Bob" bob.money = 100 give_money(bob) print(bob.money)


And review it in www.pythontutor.com

ref_functAs you can see in this example the function takes as an argument a person which is a memory address of the object. Think of it as a bank account number. The function uses this copy of the account number to deposit 100 euros. This causes Bob's bank account balance to go up.

Exercise 1

In Thonny's scripting area create a program as follows:

  • Create a class called Cat with attributes for name, color and weight.
  • Create a method inside the class called meow.
  • Create an instance of the cat class, set the attributes, and call the meow method.

Exercise 1 answer

Exercise 2

In Thonny's scripting area create a program as follows:

  • Create a class called Monster with attributes name and an integer attribute for health.
  • Create a method called decrease_health that takes in a parameter amount and decreases the health by that much.
  • Inside that method, print that the animal died if health goes below zero.

Exercise 2 answer

7.1.7 - Constructors

In the previous chapter we have created objects (instances of a class) and after the creation we added the fields as name, color, weight, etc.

This is not convenient and not completely correct because the time a new object is created is empty. To avoid it, we are using a constructor of an object inside the class definition.

Review the code below (www.pythontutor.com)

class Dog(): def __init__(self, new_name): """ Constructor. """ self.name = new_name print("A new dog is born. It's name is " + new_name + ".") my_dog=Dog("Spot")


The init function in this code has an argument except self. This is the self.name of the new object. Also inside the init we can print a message to be informed of the new object.

Copy the code that creates the class to Thonny script area and save it classConstructor.

At the CLI area try to create a new dog object with a name and without a name.

>>> my_dog = Dog("Pythos")

>>> my_dog = Dog()