Python object and class

To assign one class(template) to an object you would do the following:

class MyClass(object):
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()

Now the variable "myobjectx" holds an object of the class "MyClass" that contains the variable and the function defined within the class called "MyClass".

You can create multiple different objects that are of the same class(have the same variables and functions defined). However, each object contains independent copies of the variables defined in the class.

Why does new class need to inherit from "object"? Do we have to do it?

In short, it's about "old vs new style python objects".

In Python 3, apart from compatibility between Python 2 and 3, inheriting it or not makes no difference. But in Python 2, there are some perks for inheriting it.

In Python 2.x (from 2.2 onwards) there's two styles of classes depending on the presence or absence of object as a base-class:

  • classic style: no inheriting

  • new style: inheriting a build-in type, object, as a base class. Using new style has some perks:

    • classmethod

    • staticmethod

    • properties with property: Create functions for managing the getting, setting and deleting of an attribute.

    • __slots__: Saves memory consumptions of a class and also results in faster attribute access.

    • The __new__ static method: lets you customize how new class instances are created.

    • Method resolution order (MRO): in what order the base classes of a class will be searched when trying to resolve which method to call.

    • Related to MRO, super calls. Also see, super() considered super.

One of the downsides of new-style classes is that the class itself is more memory demanding. Unless you're creating many class objects, though, this might just be an issue and it's a negative sinking in a sea of positives.

In Python 3.x, things are simplified. Only new-style classes exist (referred to plainly as classes) so, the only difference in adding object is requiring you to type in 8 more characters.

In summary, what should we do? In Python 2: always inherit from object explicitly. Get the perks. In Python 3: inherit from object if you are writing code that tries to be Python agnostic, that is, it needs to work both in Python 2 and in Python 3. Otherwise don't, it really makes no difference since Python inserts it for you behind the scenes.

Last updated