Python Series Part 11: Classes

Jarret B

Well-Known Member
Staff member
Joined
May 22, 2017
Messages
373
Reaction score
444
Credits
13,805
Classes in Python are special objects that you create. The classes can have attributes that define the class.

Once we fill the attributes in the class and give it definition, we have an object.

Creating a Class

Let me give an example to help clear this up.

We can have a class named 'rectangle'. The class has attributes, like 'length' and 'width'.

Let's create the class first:

Code:
class rectangle():

We now have a class, but no attributes. As we saw above, let's give this class some attributes:

Code:
class rectangle():
    def length(self):
    def width(self):

The 'self' variable here refers to the attribute itself. It is required and can be any variable, but common practice is to use 'self'. We can pass other arguments as needed.

Each attribute can comprise a single or multiple command. Let's look at an example:

Code:
def length(self)
    rectangle.length = input("What is the rectangle's length?\n")

Here, when we call rectangle's attribute of 'length', we get an input value from the user for the length of the rectangle. We set the value input by the user to the attribute. We can do the same with the rectangle's width:

Code:
def width(self)
    rectangle.width = input("What is the rectangle's width?\n")

We can now add to the entire program:

Code:
class rectangle():
    def length(self):
        rectangle.length = input("What is the rectangle's length?\n")
    def width(self):
        rectangle.width = input("What is the rectangle's width?\n")

shape1 = rectangle()
shape1.length()
shape1.width()
print(f"The length is: {shape1.length}")
print(f"The width is: {shape1.width}")


The code creates an object called 'shape1' that is a rectangle and has two attributes, length and width.

What if we wanted to add another class of attributes that differ from those in 'rectangle'?

Class Inheritance

We can create a class in a class and allow the 'parent' class, in this case it is the 'rectangle' class to inherit attributes from the 'child' class.

Let's look at an example of a 'child' class:

Code:
class measurements:
    def perimeter(self, width, length):
        print(f"Perimeter is: {(2 * int(length)) + (2 * int(width))}")
    def footage(self, width, length):
        print(f"Footage is: {int(length) * int(width)}")

This may look exactly like the 'rectangle' class. Here, we pass the arguments 'length' and 'width' to the class attribute. The arguments are used to perform calculations, or measurements, on the information passed to them.

I could have easily used 'rectangle.width' and 'rectangle.length' instead of passing the arguments, but we will try to reuse the classes for something else.

So, to add this as a child class, we perform:

Code:
class rectangle(measurements):

Let's look at the code now for the entire program with a few additions that should help make things a little clearer:


Code:
class measurements:
    def perimeter(self, width, length):
       print(f"Perimeter is: {(2 * int(length)) + (2 * int(width))}")
   def footage(self, width, length):
        print(f"Footage is: {int(length) * int(width)}")

class rectangle(measurements):
    def length(self):
        rectangle.length = input("What is the rectangle's length?\n")
    def width(self):
        rectangle.width = input("What is the rectangle's width?\n")

shape1 = rectangle()
shape1.length()
shape1.width()
print(f"The length is: {shape1.length}")
print(f"The width is: {shape1.width}")
shape1.perimeter(shape1.width, shape1.length)
shape1.footage(shape1.width, shape1.length)


Now, we can call the attribute 'perimeter' and 'footage' for 'shape1' and it will calculate the attributes and print out the information. We can easily store the calculation as we did for the input of the width and length to calculate outside of the class code.

As I had mentioned, we can do something else with the class code. We can re-use it. Let's add another class named 'square'. We can ask for the length of one side. For a square, all sides are the same, so we only need to ask for one side:

Code:
class square(measurements):
    def length(self):
        square.length = input("What is the square's length?\n")
    def width(self):
        square.width = square.length

We let the user input the 'length', the when we call the 'width', we just duplicate it from the 'length'. As you can see, it is a parent of 'measurements'. The class 'measurements' are re-used for the new 'square' class.

Now the code is more like:

Code:
class measurements:
    def perimeter(self, width, length):
        print(f"Perimeter is: {(2 * int(length)) + (2 * int(width))}")
    def footage(self, width, length):
        print(f"Footage is: {int(length) * int(width)}")

class rectangle(measurements):
    def length(self):
        rectangle.length = input("What is the rectangle's length?\n")
    def width(self):
        rectangle.width = input("What is the rectangle's width?\n")

class square(measurements):
    def length(self):
        square.length = input("What is the square's length?\n")
    def width(self):
         square.width = square.length

shape1 = rectangle()
shape1.length()
shape1.width()
shape1.perimeter(shape1.width, shape1.length)
shape1.footage(shape1.width, shape1.length)
shape2 = square()
shape2.length()
shape2.width()
shape2.perimeter(shape2.width, shape2.length)
shape2.footage(shape2.width, shape2.length)

Initializing

When you create an object, this calls the initialization method (init) for the class. Let's look at an example:

Code:
class test2():
    def look2(self):
        print("Test2: ", self.name)

class test(test2):
    def __init__(self, name1):
       self.name = name1
    def look(self):
        print("Test: ", self.name)

variable=test("Tux")
variable.look()
variable.look2()

Here, we are setting up a parent and child class. When we initialize the object, in the line 'variable = test("Tux)', it calls the 'init' method and places the parameter 'Tux' into 'self.name'. Remember that 'self' is the class, so we place the parameter, 'Tux', into the 'self.name' variable.

After initialization, we look at the method 'look' which prints out the contents of 'self.name'. After calling 'look', we call 'look2' in the child class, which prints out the same variable.

In both cases, we get the output of 'Tux'. Keep in mind that it keeps the variables within the classes that are related, parent and child.

If we were to add another class but not relate it to any of the others, it would not carry the variable 'self.name' over.

The 'init' method is built-in to each class you create. Once you initialize the object, this method is called.

Duplicate Method Order

If you have two methods, one in the parent and the other in the child, that have the same names, it uses the method in the child class . Let me give an example:

Code:
class child():
    def talk(self):
        print("Child's conversation.")

class parent(child):
    def talk(self):
        print ("Parent's conversation.")

value = parent()
value.talk()

The result here is the output of 'Parent's conversation."

Multiple Inheritance

We can inherit methods from multiple classes. It can be two or more, but let's look at an example of using two classes:

Code:
class twodmeasurements:
    def perimeter(self, width, length):
        print(f"Perimeter is: {(2 * int(length)) + (2 * int(width))}")
    def footage(self, width, length):
        print(f"Footage is: {int(length) * int(width)}")

class threedmeasurements:
    def volume(self):
        depth = input("What is the depth of the rectangular box?\n")
        print(f"Volume is: {int(rectangle.length) * int(rectangle.width) * int(depth)}")

class rectangle(twodmeasurements, threedmeasurements):
    def length(self):
        rectangle.length = input("What is the rectangle's length?\n")
    def width(self):
        rectangle.width = input("What is the rectangle's width?\n")

In the example, I've stored the values of 'length' and 'width' in the class variables starting with 'rectangle.' and not 'self.'.

Here, we place the parent class (rectangle) with two child classes (twodmeasurements and threedmeasurements).

Conclusion

There is definitely more than we can cover in articles about classes. This is an excellent base to learn about classes.

Try a few examples of your own to figure out how classes work because they can be beneficial in some programs.
 


Top