Home > Articles > Programming > Python

Objects and Classes in Python

  • Print
  • + Share This
Learn the basics of object-oriented programming through Python's classes and inheritance and see where Python diverges from other OO languages.
This chapter is from the book

This chapter is from the book

This chapter presents details on Python's classes and inheritance, the facilities essential for object-oriented programming. The classes contain methods, functions that apply to class instances. These methods access and assign attributes of the instance. Python provides multiple inheritance, so you can use methods of more than one superclass to manipulate an instance. Multiple inheritance can be confusing if there is more than one way to inherit from the same superclass, so-called diamond inheritance.

Unlike statically-typed object-oriented languages, you do not have to use inheritance in Python. All that is required is that an object have a method with the proper name and parameters available when you call it. There are no visibility restrictions on attribute names in instances that are used by methods in different classes.

4.1 Instances and Classes

You create a class object by executing a class statement, e.g.:

class point: pass

You create an instance of a class by calling the class name as a function:


Both classes and instance objects have attributes. You get an attribute with the syntax:

object . attribute_name

The instance has a reference to its class in a special attribute __class__, so that p.__class__ is point.

Both classes and class instances have dictionaries, named __dict__. You reference the class point's dictionary as point.__dict__ and the instance p's dictionary as p.__dict__. The relationships between p and point and their dictionaries are shown in Figure 4–1.

Figure 4-1Figure 4-1 Instances and classes.

  • + Share This
  • 🔖 Save To Your Account