Skip to content

Chapter 9: Classes

Jarlin Almanzar edited this page Nov 22, 2019 · 5 revisions

Classes

In object-oriented programming you write classes that represent real-world things and situations, and you create objects based on these classes.

Making an object from a class is called instantiation, and you work with instances of a class.

Creating and Using a Class

Example a Dog Class

class Dog:
    """ A model of a dog """
    def __init__(self, name, age):
        """ Inialize name and age attributes """
        self.name = name
        self.age = age

    def sit(self):
        """ Stimulate a dog sitting command """
        print(f"{self.name} is now sitting.")

    def roll_over(self):
        """ Stimulate a dog rolling over command """
        print(f"{self.name} rolled over!")

The init() method

A function that's part of a class is a method.
A special method that python runs automatically whenever we create a new instance based on the class.

The self parameter

The self parameter is required in the method definition, and it must come first before the other parameters. Self must be include, as Python passes the self argument.

How to use the instance

When we call the dog instance for example, we don't need to call self.
We call upon all the other arguments.

import dog

my_dog = dog.Dog('Willie', '6')

print(my_dog.name, my_dog.age)
my_dog.sit()

Inheritance

class Dog:
    """ A model of a dog """
    def __init__(self, name, age):
        """ Inialize name and age attributes """
        self.name = name
        self.age = age

    def sit(self):
        """ Stimulate a dog sitting command """
        print(f"{self.name} is now sitting.")

    def roll_over(self):
        """ Stimulate a dog rolling over command """
        print(f"{self.name} rolled over!")



class puppy(Dog):
    def __init__(self, name, age):
        super().__init__(name, age)

    def get_desc(self):
        return f"{self.name} is {self.age} years old!"
my_dog = puppy('Paw', '1')
print(my_dog.get_desc())

Overriding

class Dog:
    """ A model of a dog """
    def __init__(self, name, age):
        """ Inialize name and age attributes """
        self.name = name
        self.age = age

    def sit(self):
        """ Stimulate a dog sitting command """
        print(f"{self.name} is now sitting.")

    def roll_over(self):
        """ Stimulate a dog rolling over command """
        print(f"{self.name} rolled over!")



class puppy(Dog):
    def __init__(self, name, age):
        super().__init__(name, age)

    def get_desc(self):
        return f"{self.name} is {self.age} years old!"

    def sit(self):
        return f"{self.name} didn't sit"
my_dog = puppy('Paw', '1')
print(my_dog.sit())
Clone this wiki locally