So far, we have been writing blocks of code in functions and running them within scripts.
We call this procedural programming
or procedure oriented programming
Python is a multi-paradigm language and it allows you to write other styles in the language.
When we call methods, we are attaching functions to objects. If we create objects in our own code, then we are following Object-oriented programming.
We can create an instance of this person:
In [4]:
class Person:
def __init__(self, name):
self.name = name
def say_name(self):
print("Hi, I am called {}".format(self.name))
jimbob = Person("Jimbob")
jimbob.say_name()
Notice the use of self
, we do not explicitly pass it as an argument but it represents the instance. This brings us back to scope
.
What would happen if we did used name
instead of self.name
in the say_name
method?
In [1]:
class Person:
person_count = 0
def __init__(self):
Person.person_count += 1
print(Person.person_count)
p = Person()
print(Person.person_count)
In [2]:
class Person:
person_count = 0
def __init__(self):
Person.person_count += 1
@staticmethod
def eat_food(): #no self passed in here
print("mmmmm")
print(Person.person_count)
p = Person()
print(Person.person_count)
Create a class for a car and create a constructor (__init__
) that sets the make, model and engine size.
Add some class variables that are general across all cars.
Create methods to get information about each instance.
Create static methods to do things with the car that would be common across all cars.
This is barely the surface to OO programming. You cover this in detail in the next semester.
When we create a class, we are given built in Python methods to run on it already (such as: print, add, multiply, type etc)
We can override
these methods in order to do our own thing when we call it.
Prove it? Use on of your classes from earlier and print
it. What is it printing? We can make that more detailed:
In [2]:
class Bella:
def __init__(self): #here is the constructor being overridden
pass
def __str__(self): #called when we call `print` on an object
return "I want you, and I want you forever. One lifetime is simply not enough for me."
b = Bella()
print(b)
That's all, Folks!