In object-oriented programming (OOP), functions are bundled with data into classes, which are used to create objects.
Here is the simplest example of a class possible in Python.
A class is defined using the class keyword, and the pass keyword is used to indicate the class has no body. Even so, it is possible to create objects using the class.
class Greeter:
pass
def main():
g = Greeter()
print(type(g))
if __name__ == "__main__":
main()
<class '__main__.Greeter'>
A Class with a Method
When a function is associated with a class, it is known as a method. This class has just one method, greet(). To call the method, we have to first create an object from the class.
Methods have a special first argument, usually called self. This is used to refer to the object that the method belongs to, as we’ll see later.
Self is supplied automatically, so here we have empty brackets when we actually call greet().
class Greeter:
def greet(self):
print("Hello!")
def main():
g = Greeter()
g.greet()
if __name__ == "__main__":
main()
Hello!
Constructors
We can implement a special method called the constructor. This is called automatically whenever an object is created from the class.
The constructor has the special name __init__.
class Greeter:
def __init__(self):
print("Greeter object created!")
def greet(self):
print("Hello!")
def main():
g1 = Greeter()
g2 = Greeter()
if __name__ == "__main__":
main()
Greeter object created!
Greeter object created!
Instance Variables
Every object can have its own associated variables. These are called instance variables (because they belong to “instances” (examples) of the class; they belong to particular objects. They’re also known as fields, attributes, or somtimes, properties.
In this code, we create a class called Greeter that has an attribute called _name and a method called greet(). The _name property is set using a parameter that’s passed to the constructor. We specify this when we create objects from the class. We then create two objects with different names.
class Greeter:
def __init__(self, name):
self._name = name
print("Greeter object created!")
def greet(self):
print(f"Hello {self._name}!")
def main():
g1 = Greeter("Bob")
g2 = Greeter("Sarah")
g1.greet()
g2.greet()
if __name__ == "__main__":
main()
Hello Bob!
Hello Sarah!
The reason _name is prefixed with an underscore is to declare that it’s “private” to the class; it should only be used within the class and should not be referred to outside of the class.
This is called encapsulation.
Unlike many OO programming languages, Python does not supply us with a way of stopping access to private variables outside the class; it trusts the programmer to know what he or she is doing.
Leave a Reply