OOP Review
Review Object-Oriented Programming in Python
Review Object-Oriented Programming in Python
Object-oriented programming uses the idea of objects and classes to provide many improvements over other programming paradigms. The key concept of object-oriented programming - encapsulation - allows our data and the operations that manipulate that data to be bundled together within a single object.
File:CPT-OOP-inheritance.svg. (2014, June 26). Wikimedia Commons, the free media repository. Retrieved 01:22, January 14, 2020 from https://commons.wikimedia.org/w/index.php?title=File:CPT-OOP-inheritance.svg&oldid=127549650. ↩︎
Functions are small pieces of reusable code that allow you to divide complex programs into smaller subprograms. Ideally, functions perform a single task and return a single value. (It should be noted that some programming languages allow for procedures, which are similar to functions but return no values. Except for the return value, it is safe to group them with functions in our discussion below.)
Functions can be thought of as black boxes. When we talk about black boxes we mean that users cannot look inside the box to see how it actually works. A good example of a black box is a soda machine. We all use them and know how to operate them, but very few of actually know how they work inside. Nor do we really want to know. We are happy to simply use them machine and have it give a nice cold soda when we are thirst!
To be able to reuse functions easily, it is important to define what a function does and how it should be called.
Before we can call a function, we must know the function’s signature. A function’s signature includes the following.
While a signature will allow us to actually call the function in code. Of course to use functions effectively, we must also know exactly what the function is supposed to do. We will talk more about how we do this in the next module on programming by contract. For now we can assume that we just have a good description of what the function does.
While we do not need to know exactly how a function actually performs its task, the algorithm used to implement the function is vitally important as well. We will spend a significant amount of time in this course designing such algorithms.
The lifecycle of a function is as follows.
When the function is called, the arguments, or actual parameters, are copied to the function’s formal parameters and program execution jumps from the “call” statement to the function. When the function finishes execution, execution resumes at the statement following the “call” statement.
In general, parameters are passed to functions by value, which means that the value of the calling program’s actual parameter is copied into the function’s formal parameter. This allows the function to modify the value of the formal parameter without affecting the actual parameter in the calling program.
However, when passing complex data structures such as objects, the parameters are passed by reference instead of by value. In this case, a pointer to the parameter is passed instead of a copy of the parameter value. By passing a pointer to the parameter, this allows the function to actually make changes to the calling program’s actual parameter.
As you might guess from its name, object-oriented programming languages are made to create and manipulate entities called objects. But what exactly are these objects? Objects were created to help decompose large complex programs with a lot of complex data into manageable parts.
An object is a programming entity that contains related data and behavior.
A good example of an object is dog. But not just any dog, or all dogs, but a specific dog. Each dog has specific characteristics that are captured as data such as their name, their height, their weight, their breed, their age, etc. We call these characteristics attributes and all dogs have the same type of attributes, although the values of those attributes may be unique. And generally, all dogs exhibit the same behaviors, or methods. Almost all dogs can walk, run, bark, eat, etc.
So, how do we define the basic attributes and behaviors of a dog? We probably start with some kind of idea of what a dog is. How do we describe dogs in general. In object orientation we do that through classes.
A class is a blueprint for an object.
What do we use blueprints for? Well, when we are building a physical structure such as a home or office building, an architect first creates a blueprint that tells the builder what to build and how everything should fit together. That is essentially what a class does. A class describes the types of attributes and methods that an object of that class will have.
Then to create objects, we say we create an instance of a class by calling the class’s constructor method, which creates an object instance in memory and makes sure it’s attributes are properly created. Once the object has been created, the methods defined by the class can be used to manipulate the attributes and internal data of the object.
Two of the most powerful concepts in object orientation are encapsulation and information hiding.
Encapsulation enables information hiding, and information hiding allows us to simplify the interface used to interact with an object. Instead of needing to know everything about a particular class of objects in order to use or interact with those objects. This will make our programs less complex and easier to implement and test. It also makes it easier for you to change the internal implementations of methods without affecting the rest of your program. As long as the method behaves in the same way (i.e., produces the same outputs given a given set of inputs), the rest of your program will not be affected. Thus, we see two key parts of any class:
Encapsulation and information hiding are actually all around us. Take for example, a soda vending machine. There are many internal parts to the machine. However, as a user, we care little about how the machine works or what it does inside. We need to simply know how to insert money or swipe our card and press a couple of buttons to get the soda we desire. If a repair is needed and an internal motor is replaced, we don’t care whether they replaced the motor with the exact same type of motor or the new model. As long as we can still get our soda by manipulating the same payment mechanisms and buttons, we are happy. You and I care only about the interface to the machine, not the implementation hiding inside.
To implement information hiding in our classes, we use visibility. In general, attributes and methods can either be public or private. If we want and attribute or method to be part of the class interface, we define them as public. If we want to hide a attribute or method from external objects, we defined them as private. An external object may access public attributes and call public methods, which is similar to using the payment mechanism or the buttons on a soda machine. However, the internals of how the object works is hidden by private attributes and methods, which are equivalent to the internal workings of the soda machine.
To implement information hiding, we recommend that you declare all attributes of a class as private. Any attribute whose value should be able to be read or changed by an external object should create special “getter” and “setter” methods that access those private variables. This way, you can make changes to the implementation of the attributes without changing how it is accessed in the external object.
Polymorphsim is a concept that describes the fact that similar objects tend to behave in similar ways, even if they are not exactly alike. For example, if we might have a set of shapes such as a square, a circle, and a rhombus. While each shape shares certain attributes like having an area and a perimeter. However, each shape is also unique and may have differing number of sides and angles between those sides, or in the case of a circle, a diameter. We describe this relationship by saying a circle (or rectangle, or rhombus) “is a” shape as shown in the figure below.
Inheritance is a mechanism that captures polymorphism by allowing classes to inherit the methods and attributes from another class. The basic purpose of inheritance to to reuse code in a principled and organized manner. We generally call the inheriting class the subclass or child class, while the class it inherits from is called the superclass or parent class.
Basically, when class ‘A’ inherits from class ‘B’, all the methods and attributes of class ‘A’ are automatically copied to class ‘B’. Class ‘B’ can then add additional methods or attributes to extend class ‘A’, or overwrite the implementations of methods in class ‘A’ to specialize it.
When programming, we use inheritance to implement polymorphism. In our shape example, we would have a generic (or abstract) Shape class, which is inherited by a set of more specific shape classes (or specializations) as shown below.
In this example, the Shape class defines the ‘color’ attribute and the ‘getArea’ and ‘getCircumference’ methods, which are inherited by the Rectangle, Circle, and Rhombus classes. Each of the subclasses define additional attributes that are unique to the definition of each shape type.
Notice that although the Shape class defines the signatures for the ‘getArea’ and ‘getCircumference’ methods, it cannot define the implementation of the methods, since this is unique to each subclass shape. Thus, each subclass shape will specialize the Shape class by implementing their own ‘getArea’ and ‘getCircumference’ methods.
So far, we have discussed Single inheritance, which occurs when a class has only one superclass. However, theoretically, a class may inherit from more than one superclass, which is termed multiple inheritance. While a powerful mechanism, multiple inheritance also introduces complexity into understanding and implementing programs. And, there is always the possibility that attributes and methods from the various superclasses contradict each other in the subclass.
For object a
to be able to call a method in object b
, object a
must have a reference (a pointer, or the address of) object b
. In many cases, objects a
and b
will be in a long-term relationship so that one or both objects will need to store the reference to the other in an attribute. When an object holds a reference to another object in an attribute, we call this a link. Examples of such relationships include a driver owning a car, a person living at an address, or a worker being employed by a company.
As we discussed earlier, objects are instances of classes. To represent this in a UML class diagram, we use the notion of an association, which is shown as a line connecting to two classes. More precisely, a link is an instance of an association. The figure belows shows three examples of an association between class A
and class B
.
The top example shows the basic layout of an association in UML. The line between the two classes denotes the association itself. The diagram specifies that ClassA
is associated with ClassB
and vice versa. We can name the association as well as place multiplicities on the relationships. The multiplicities show exactly how many links an object of one class must have to objects of the associated class. The general form a multiplicity is n .. m
, which means that an object must store at least n
, but no more than m
references to other objects of the associated class; if only one number is given such as n
, then the object must store exactly n
references to objects in the associated class.
There are two basic types of associations.
The middle example shows a two-way association between ClassA
and ClassB
. Furthermore, each object of ClassA
must have a link to exactly three objects of ClassB
, while each ClassB
object must have a link with exactly one ClassA
object. (Note that the multiplicity that constrains ClassA
is located next to ClassB
, while the multiplicity that constrains ClassB
is located next to ClassA
.)
The bottom example shows a one-way association between ClassA
and ClassB
. In this case, ClassA
must have links to either zero or one objects of ClassB
. Since it is a one-way association, ClassB
will have no links to objects of ClassA
.
In Python, we can break our programs up into individual functions, which are individual routines that we can call in our code. Let’s review how to create functions in Python.
The table below lists the flowchart blocks used to represent functions, as well as the corresponding pseudocode:
Operation | Flowchart | Pseudocode |
---|---|---|
Declare Function |
|
|
Call Function |
|
In general, a function definition in Python needs a few elements. Let’s start at the simplest case:
def foo():
print("Foo")
return
Let’s break this example function definition down to see how it works:
def
at the beginning of this function definition. That keyword tells Python that we’d like to define a new function. We’ll need to include it at the beginning of each function definition.foo
. We can name a function using any valid identifier in Python. In general, function names in Python always start with a lowercase letter, and use underscores between the words in the function name if it contains multiple words.()
that list the parameters for this function. Since there is nothing included in this example, the function foo
does not require any parameters.:
indicating that the indented block of code below this definition is contained within the function. In this case, the function will simply print Foo
to the terminal.return
keyword. Since we aren’t returning a value, we aren’t required to include a return
keyword in the function. However, it is helpful to know that we may use that keyword to exit the function at any time.Once that function is created, we can call it using the following code:
foo()
In a more complex case, we can declare a function that accepts parameters and returns a value, as in this example:
def count_letters(input, letter):
output = 0
for i in range(0, len(input)):
if input[i] == letter:
output += 1
return output
In this example, the function accepts two parameters: input
, which could be a string, and letter
, which could be a single character. However, since Python does not enforce a type on these parameters, they could actually be any value. We could add additional code to this function that checks the type of each parameter and raises a TypeError
if they are not the expected type.
We can use the parameters just like any other variable in our code. To return a value, we use the return
keyword, followed by the value or variable containing the value we’d like to return.
To call a function that requires parameters, we can include values as arguments in the parentheses of the function call:
sum += count_letters("The quick brown fox jumped over the lazy dog", "e")
Python allows us to specify default values for parameters in a function definition. In that way, if those parameters are not provided, the default value will be used instead. So, it may appear that there are multiple functions with the same name that accept a different number of parameters. This is called function overloading.
For example, we could create a function named max()
that could take either two or three parameters:
def main():
max(2, 3)
max(3, 4, 5)
def max(x, y, z=None):
if z is not None:
if x >= y:
if x >= z:
print(x)
else:
print(z)
else:
if y >= z:
print(y)
else:
print(z)
else:
if x >= y:
print(x)
else:
print(y)
# main guard
if __name__ == "__main__":
main()
In this example, we are calling max()
with both 2 and 3 arguments from main()
. When we only provide 2 arguments, the third parameter will be given the default value None
, which is a special value in Python showing that the variable is empty. Then, we can use if z is not None
as part of an If-Then statement to see if we need to take that variable into account in our code.
This example also introduces a new keyword, is
. The is
keyword in Python is used to determine if two variables are exactly the same object, not just the same value. In this case, we want to check that z
is exactly the same object as None
, not just that it has the same value. In Python, it is common to use the is
keyword when checking to see if an optional parameter is given the value None
. We’ll see this keyword again in a later chapter as we start dealing with objects.
Python also allows us to specify function arguments using keywords that match the name of the parameter in the function. In that way, we can specify the arguments we need, and the function can use default values for any unspecified parameters. Here’s a quick example:
def main():
args(1) # 6
args(1, 5) # 9
args(1, c=5) # 8
args(b=7, a=2) # 12
args(c=5, a=2, b=3) # 10
def args(a, b=2, c=3):
print(str(a + b + c))
# main guard
if __name__ == "__main__":
main()
In this example, the args()
method has one required parameter, a
. It can either be provided as the first argument, known as a positional argument, or as a keyword argument like a=2
. The other parameters, b
and c
, can either be provided as positional arguments or keyword arguments, but they are not required since they have default values.
Also, we can see that when we use keyword arguments we do not have to provide the arguments in the order they are defined in the function’s definition. However, any arguments provided without keywords must be placed at the beginning of the function call, and will be matched positionally with the first parameters defined in the function.
Finally, Python allows us to define a single parameter that is a variable length parameter. In essence, it will allow us to accept anywhere from 0 to many arguments for that single parameter, which will then be stored in a list. Let’s look at an example:
def main():
max(2, 3)
max(3, 4, 5)
max(5, 6, 7, 8)
max(10, 11, 12, 13, 14, 15, 16)
def max(*values):
if len(values) > 0:
max = values[0]
for value in values:
if value > max:
max = value
print(max)
# main guard
if __name__ == "__main__":
main()
Here, we have defined a function named max()
that accepts a single variable length parameter. To show a parameter is variable length we use an asterisk *
before variable name. We must respect two rules when creating a variable length parameter:
So, when we run this program, we see that we can call the max()
function with any number of arguments, and it will be able to determine the maximum of those values. Inside of the function itself, values
can be treated just like a list.
In programming, a class describes an individual entity or part of the program. In many cases, the class can be used to describe an actual thing, such as a person, a vehicle, or a game board, or a more abstract thing such as a set of rules for a game, or even an artificial intelligence engine for making business decisions.
In object-oriented programming, a class is the basic building block of a larger program. Typically each part of the program is contained within a class, representing either the main logic of the program or the individual entities or things that the program will use.
We can represent the contents of a class in a UML Class Diagram. Below is an example of a class called Person
:
Throughout the next few pages, we will realize the design of this class in code.
To create a class in Python, we can simply use the class
keyword at the beginning of our file:
class Person:
pass
As we’ve already learned, each class declaration in Python includes these parts:
class
- this keyword says that we are declaring a new class.Person
- this is an identifier that gives us the name of the class we are declaring.Following the declaration, we see a colon :
marking the start of a new block, inside of which will be all of the fields and methods stored in this class. We’ll need to indent all items inside of this class, just like we do with other blocks in Python.
In order for Python to allow this code to run, we cannot have an empty block inside of a class declaration. So, we can add the keyword pass
to the block inside of the class so that it is not empty.
By convention, we would typically store this class in a file called Person.py
.
Of course, our classes are not very useful at this point because they don’t include any attributes or methods. Including attributes in a class is one of the simplest uses of classes, so let’s start there.
To add an attribute to a class, we can simply declare a variable inside of our class declaration:
class Person:
last_name = "Person"
first_name = "Test"
age = 25
That’s really all there is to it! These are static attributes or class attributes that are shared among all instances of the class. On the next page, we’ll see how we can create instance attributes within the class’s constructor.
Finally, we can make these attributes private by adding two underscores to the variable’s name. We denote this on our UML diagram by placing a minus -
before the attribute or method’s name. Otherwise, a +
indicates that it should be public. In the diagram above, each attribute is private, so we’ll do that in our code:
class Person:
__last_name = "Person"
__first_name = "Test"
__age = 25
Unfortunately, Python does have a way to get around these restrictions as well. Instead of referencing __last_name
, we can instead reference _Person__last_name
to find that value, as in this example:
ellie = Person("Jonson", "Ellie", 29)
ellie._Person__last_name = "Jameson"
print(ellie.last_name) # Jameson
Behind the scenes, Python adds an underscore _
followed by the name of the class to the beginning of any class attribute or method that is prefixed with two underscores __
. So, knowing that, we can still access those attributes and methods if we want to. Thankfully, it’d be hard to do this accidentally, so it provides some small level of security for our data.
We can also add methods to our classes. These methods are used either to modify the attributes of the class or to perform actions based on the attributes stored in the class. Finally, we can even use those methods to perform actions on data provided as arguments. In essence, the sky is the limit with methods in classes, so we’ll be able to do just about anything we need to do in these methods. Let’s see how we can add methods to our classes.
A constructor is a special method that is called whenever a new instance of a class is created. It is used to set the initial values of attributes in the class. We can even accept parameters as part of a constructor, and then use those parameters to populate attributes in the class.
Let’s go back to the Person
class example we’ve been working on and add a simple constructor to that class:
class Person:
__last_name = "Person"
__first_name = "Test"
__age = 25
def __init__(self, last_name, first_name, age):
self.__last_name = last_name
self.__first_name = first_name
self.__age = age
Since the constructor is an instance method, we need to add a parameter to the function at the very beginning of our list of parameters, typically named self
. This parameter is automatically added by Python whenever we call an instance method, and it is a reference to the current instance on which the method is being called. We’ll learn more about this later.
Inside that constructor, notice that we use each parameter to set the corresponding attribute, using the self
keyword once again to refer to the current object.
Also, since we are now defining the attributes as instance attributes in the constructor, we can remove them from the class definition itself:
class Person:
def __init__(self, last_name, first_name, age):
self.__last_name = last_name
self.__first_name = first_name
self.__age = age
We’ve already discussed variable scope earlier in this course. Recall that two different functions may use the same local variable names without affecting each other because they are in different scopes.
The same applies to classes. A class may have an attribute named age
, but a method inside of the class may also use a local variable named age
. Therefore, we must be careful to make sure that we access the correct variable, using the self
reference if we intend to access the attribute’s value in the current instance. Here’s a short example:
class Test:
age = 15
def foo(self):
age = 12
print(age) # 12
print(self.age) # 15
def bar(self):
print(self.age) # 15
print(age) # NameError
As we can see, in the method foo()
we must be careful to use self.age
to refer to the attribute, since there is another variable named age
declared in that method. However, in the method bar()
we see that age
itself causes a NameError
since there is no other variable named age
defined in that scope. We have to use self.age
to reference the attribute.
So, we should always get in the habit of using self
to refer to any attributes, just to avoid any unintended problems later on.
In Python, we can use a special decorator @property
to define special methods, called getters and setters, that can be used to access and update the value of private attributes.
In Python, a getter method is a method that can be used to access the value of a private attribute. To mark a getter method, we use the @property
decorator, as in the following example:
class Person:
def __init__(self, last_name, first_name, age):
self.__last_name = last_name
self.__first_name = first_name
self.__age = age
@property
def last_name(self):
return self.__last_name
@property
def first_name(self):
return self.__first_name
@property
def age(self):
return self.__age
Similarly, we can create another method that can be used to update the value of the age
attribute:
class Person:
def __init__(self, last_name, first_name, age):
self.__last_name = last_name
self.__first_name = first_name
self.__age = age
@property
def last_name(self):
return self.__last_name
@property
def first_name(self):
return self.__first_name
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
self.__age = value
However, this method is not required in the UML diagram, so we can omit it.
To add a method to our class, we can simply add a function declaration inside of our class.
class Person:
def __init__(self, last_name, first_name, age):
self.__last_name = last_name
self.__first_name = first_name
self.__age = age
@property
def last_name(self):
return self.__last_name
@property
def first_name(self):
return self.__first_name
@property
def age(self):
return self.__age
def happy_birthday(self):
self.__age = self.age + 1
Notice that once again we must remember to add the self
parameter as the first parameter. This method will update the private age
attribute by one year.
Now that we have fully constructed our class, we can use it elsewhere in our code through the process of instantiation. In Python, we can simply call the name of the class as a method to create a new instance, which calls the constructor, and then we can use dot-notation to access any attributes or methods inside of that object.
from Person import *
john = Person("Smith", "John", 25)
print(john.last_name)
john.happy_birthday()
Notice that we don’t have to provide a value for the self
parameter when we use any methods. This parameter is added automatically by Python based on the value of the object we are calling the methods from.
We can also build classes that inherit attributes and methods from another class. This allows us to build more complex structures in our code, better representing the relationships between real world objects.
As we learned earlier in this chapter, we can represent an inheritance relationship with an open arrow in our UML diagrams, as shown below:
In this diagram, the Student
class inherits from, or is a subclass of, the Person
class.
To show inheritance in Python, we place the parent class inside of parentheses directly after the name of the subclass when it is defined:
from Person import *
class Student(Person):
pass
From there, we can quickly implement the code for each property and getter method in the new class:
from Person import *
class Student(Person):
@property
def student_id(self):
return self.__student_id
@property
def grade_level(self):
return self.__grade_level
Since the subclass Student
also includes a definition for the method happy_birthday()
, we say that that method has been overridden in the subclass. We can do this by simply creating the new method in the Student
class, making sure it accepts the same number of parameters as the original:
from Person import *
class Student(Person):
@property
def student_id(self):
return self.__student_id
@property
def grade_level(self):
return self.__grade_level
def happy_birthday(self):
super().happy_birthday()
self.__grade_level += 1
Here, we are using the function super()
to refer to our parent class. In that way, we can still call the happy_birthday()
method as defined in Person
, but extend it by adding our own code as well.
In addition, we can use the super()
method to call our parent class’s constructor.
from Person import *
class Student(Person):
@property
def student_id(self):
return self.__student_id
@property
def grade_level(self):
return self.__grade_level
def __init__(self, last_name, first_name, age, student_id, grade_level):
super().__init__(last_name, first_name, age)
self.__student_id = student_id
self.__grade_level = grade_level
def happy_birthday(self):
super().happy_birthday()
self.__grade_level += 1
In addition to private and public attributes and methods, UML also includes the concept of protected methods. This modifier is used to indicate that the attribute or method should not be accessed outside of the class, but will allow any subclasses to access them. Python does not enforce this restriction; it is simply convention. In a UML diagram, the protected keyword is denoted by a hash symbol #
in front of the attribute or method. In Python, we then prefix those attributes or methods with a single underscore _
.
Inheritance allows us to make use of polymorphism in our code. Loosely polymorphism allows us to treat an instance of a class within the data type of any of its parent classes. By doing so, we can only access the methods and attributes defined by the data type, but any overriden methods will use the implementation from the child class.
Here’s a quick example:
steve_student = new Student("Jones", "Steve", "19", "123456", "13")
# We can now treat steve_student as a Person object
steve_person = steve_student
print(steve_person.first_name)
# We can call happy_birthday(), and it will use
# the code from the Student class, even if we
# think that steve_student is a Person object
steve_person.happy_birthday()
# We can still treat it as a Student object as well
print(steve_person.grade_level) # 14
Polymorphism is a very powerful tool in programming, and we’ll use it throughout this course as we develop complex data structures.
Many programming languages include a special keyword static
. In essence, a static
attribute or method is part of the class in which it is declared instead of part of objects instantiated from that class. If we think about it, the word static means “lacking in change”, and that’s sort of a good way to think about it.
In a UML diagram, static attributes and methods are denoted by underlining them.
In Python, any attributes declared outside of a method are class attributes, but they can be considered the same as static attributes until they are overwritten by an instance. Here’s an example:
class Stat:
x = 5 # class or static attribute
def __init__(self, an_y):
self.y = an_y # instance attribute
In this class, we’ve created a class attribute named x
, and a normal attribute named y
. Here’s a main()
method that will help us explore how the static keyword operates:
from Stat import *
class Main:
def main():
some_stat = Stat(7)
another_stat = Stat(8)
print(some_stat.x) # 5
print(some_stat.y) # 7
print(another_stat.x) # 5
print(another_stat.y) # 8
Stat.x = 25 # change class attribute for all instances
print(some_stat.x) # 25
print(some_stat.y) # 7
print(another_stat.x) # 25
print(another_stat.y) # 8
some_stat.x = 10 # overwrites class attribute in instance
print(some_stat.x) # 10 (now an instance attribute)
print(some_stat.y) # 7
print(another_stat.x) # 25 (still class attribute)
print(another_stat.y) # 8
if __name__ == "__main__":
Main.main()
First, we can see that the attribute x
is set to 5 as its default value, so both objects some_stat
and another_stat
contain that same value. Interestingly, since the attribute x
is static, we can access it directly from the class Stat
, without even having to instantiate an object. So, we can update the value in that way to 25, and it will take effect in any objects instantiated from Stat
.
Below that, we can update the value of x
attached to some_stat
to 10, and we’ll see that it now creates an instance attribute for that object that contains 10, overwriting the previous class attribute. The value attached to another_stat
is unchanged.
Python also allows us to create static methods that work in a similar way:
class Stat:
x = 5 # class or static attribute
def __init__(self, an_y):
self.y = an_y # instance attribute
@staticmethod
def sum(a):
return Stat.x + a
We have now added a static method sum()
to our Stat
class. To create a static method, we place the @staticmethod
decorator above the method declaration. We haven’t learned about decorators yet, but they allow us to tell Python some important information about the code below the decorator.
In addition, it is important to remember that a static method cannot access any non-static attributes or methods, since it doesn’t have access to an instantiated object in the self
parameter.
As a tradeoff, we can call a static method without instantiating the class either, as in this example:
from Stat import *
class Main:
@staticmethod
def main():
# other code omitted
Stat.x = 25
moreStat = Stat(7)
print(moreStat.sum(5)) # 30
print(Stat.sum(5)) # 30
if __name__ == "__main__":
Main.main()
This becomes extremely useful in our main()
method. Since we aren’t instantiating our Main
class, we can use the decorator @staticmethod
above the method to clearly mark that it should be considered a static method.
Another major feature of class inheritance is the ability to define a method in a parent class, but not provide any code that implements that function. In effect, we are saying that all objects of that type must include that method, but it is up to the child classes to provide the code. These methods are called abstract methods, and the classes that contain them are abstract classes. Let’s look at how they work!
In the UML diagram above, we see that the describe()
method in the Vehicle
class is printed in italics. That means that the method should be abstract, without any code provided. To do this in Python, we simply inherit from a special class called ABC
, short for “Abstract Base Class,” and then use the @abstractmethod
decorator:
from abc import ABC, abstractmethod
class Vehicle(ABC):
def __init__(self, name):
self.__name = name
self._speed = 1.0
@property
def name(self):
return self.__name
def move(self, distance):
print("Moving");
return distance / self._speed;
@abstractmethod
def describe(self):
pass
Notice that we must first import both the ABC
class and the @abstractmethod
decorator from a library helpfully called ABC
. Then, we can use ABC
as the parent class of our class, and update each method using the @abstractmethod
decorator before the method, similar to how we’ve already used @staticmethod
in an earlier module.
In addition, since we have declared the method describe()
to be abstract, we can either add some code to that method that can be called using super().describe()
from a child class, or we can simply choose to use the pass
keyword to avoid including any code in the method.
Now, any class that inherits from the Vehicle
class must provide an implementation for the describe()
method. If it does not, that class must also be declared to be abstract. So, for example, in the UML diagram above, we see that the MotorVehicle
class does not include an implementation for describe()
, so we’ll also have to make it abstract.
Of course, that means that we’ll have to inherit from both Vehicle
and ABC
. In Python, we can do that by simply including both classes in parentheses after the subclass name, separated by a comma.
This chapter covered the rest of the programming basics we’ll need to know before starting on the new content of this course. By now we should be pretty familiar with the basic syntax of the language we’ve chosen, as well as the concepts of classes, objects, inheritance, and polymorphism in object-oriented programming. Finally, we’ve explored the Model-View-Controller (MVC) architecture, which will be used extensively in this course.