Python language basics 71: continuing with classes
December 12, 2015 2 Comments
Introduction
In the previous post we started discussing classes. We said that classes are the models for objects. The objects are instantiated based on the classes. A class describes the properties for the objects. E.g. a Car class can have a number of variables, such as colour, make, etc. A class can not only contain simple properties, but methods as well, as we’ll see later. Also, a class controls how an object can be instantiated.
Constructors and initialisers
Every class has a special function through which a new object can be instantiated. It’s called a constructor. As the name suggests it is used to construct something, in this case an object. In reality it’s only a normal function that returns an instance of the object that the class models. However, it has a special name to differentiate it from other types of methods within the class. Another frequent name for constructors is initializer, although they are not the same:
- A constructor is used to construct a brand new object instance from a class
- An initializer will configure an already existing object
We’ll see an example of a constructor in this post and examine initializers in the next.
The class keyword
A class is defined by the “class” keyword in Python, just like in probably every object-oriented language. If you’re coming from the world of strictly typed object-oriented languages, like Java or C#, then you’ll find Python classes somewhat odd at first. At least I found it difficult to get used to the lack of strictness, such as access modifiers.
Let’s start out with something simple and define a Person class with a method called shout in a separate file, e.g. “domains.py”:
class Person: def shout(self): print("HELLOOOOO")
We define class methods just like normal methods but the first argument must be “self”. Self is a built-in keyword in Python to denote that the method is applied to the object and can be called with the dot notation. It is similar to “this” in Java and C#.
A Person can be constructed through its constructor which doesn’t actually need any special declaration. Note how we import the Person class from the domains.py file:
from domains import Person person = Person() person.shout()
This prints “HELLOOOOO” in the output window.
Notice how we called Person() just like we call a normal method. That is the Person constructor. It returns a fresh instance of the Person class, i.e. an object of type Person. We can then call the shout method on the Person object with the dot notation just like we saw before in the case of built-in object types:
capital.upper() capitals_upper_long.append "Before: {0}".format(sizes) etc...
We’ll explore initializers in the next post.
Read all Python-related posts on this blog here.
Pingback: Python language basics 71: continuing with classes | Dinesh Ram Kali.
Pingback: Python language basics 72: object initializers and class level properties | Dinesh Ram Kali.