OOP In Python: Object Oriented Programming Python with Examples

(Last Updated On: April 2, 2021)

Object oriented programming or OOP in Python:

OOP in Python– First of all Python is not a primarily object oriented programming language. You don’t need to know the concepts of object orientation to be excellent Develop Python programs. Object orientation or OO for short can help to better structure the code of large projects and so to organize, so that you can reuse parts of your code later in other projects.

Basically you have to differentiate whether you are only using classes and objects or if you want to develop classes yourself. The former is perfect uncomplicated. An example: You want a character string convert to lowercase. It works like this:

In this tiny program, s1 and s2 are variables that refer to objects. These objects are instances, that is to say concrete realizations the class s1.lower is a method of this class. Methods act like functions, but automatically refer to the data of an object. The str class is special in that, it is a deep in Python integrated data type. So you can just put a new str object in of the form s1 = ‘abc’. With ordinary classes, however, you create objects with an assignment of the type var = name(), where name is the name of the class.

var then points to an object of this class. This is called in the OO nomenclature Object an instance of the class. Many classes can pass parameters to name() to initialize the object with data immediately. As soon as you have an object of this class, you can use it, e.g . its methods call up or read out or change its data:

So you see: Using objects is very easy and works even if you do not know the underlying concepts of object oriented programming in python.

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Define your own classes

In the following sections we assume that you are familiar with the ideas of object orientation. Because you already know C++, C #, or Java. There is simply not enough space in this series of articles for a proper OO introduction. Instead, on the following articles we will focus on showing you how you can apply your OO knowledge to Python to define your own classes.

Like functions, classes must be defined before they can be used. The code of a class usually consists of definitions of functions, which are called methods in the context of classes or objects. It is common to start class names with an uppercase letter. This convention is not mandatory, but increases the readability of the code, especially for other programmers. Variable and method names, on the other hand, begin with Lowercase letters.

Python Methods

Methods are mostly called in the form obj.methode(para1, para2) to edit the instance of the class identified by the variable obj. The instance is passed to the first parameter of the method. It is common for this parameter to call self:

Internally, obj.methode (1, 2) corresponds to calling class.methode (obj, 1, 2):

You can also define static methods without the self parameter. These are then called in the form MyClass.method (…), not in the form obj.method (…).

To Python, self is a parameter like any other. In this respect, Python knows about the above method does not determine whether x does not play the role of self. Should you use the incorrectly call the method defined above in the form object method (1, 2) Python returned an error because the parameter count is incorrect. That looks surprising at first glance – there are two parameters. But remember: Behind the scenes, obj.method (1, 2) is equivalent to calling MyClass(obj, 1, 2), and there is one parameter too!

You can avoid such errors by defining the method Prepend @staticmethod. In Python nomenclature, @xxx is a decorator. They provide (decorate) the method with additional information. Python now knows that the method should only be used statically and now accepts Surprisingly, also the call obj.methode (1, 2). Internally, the call corresponds but now – as intended – the call MeineKlasse (1, 2).

Python Constructor

If you want to equip your class with a constructor, that is, with code that done initializing a new instance of the class, name this method init. The data that you entered when creating, specify new object instance.

Python Class variables and namespaces

In principle, the same rules apply to class variables as to ordinary variables in Python: A previous declaration is not required. A class variable arises as soon as self.name = … is executed in the code of the class. Class variables can also be created later when using an object – with example above e.g.  by assigning obj.c = … class variables can be given by del self.name in the class or deleted outside by del obj.name.

As usual in Python, class variables are not declared. They arise through the assignment self.name = … in a method of a class. The dynamic nature from Python allows classes or objects to be added later using other methods or add variables:

Internally, Python uses Python for each class as well as for each object instance derived from it its own namespace. In the case of a class, this contains Namespace all methods initially, whereby the methods are exact taken, it is also about variables (attributes), but not to data, but to refer to functions. It should be in a class, outside of the class Methods that give code, this code is also executed when the class is read and can also create and initialize class variables Code used instead of or in addition to the constructor. The next example shows this:

Namespaces have two tasks: On the one hand, they make sure that there are no conflicts between variables with the same name inside and outside a class or of an object there. On the other hand, the namespace serves as a kind of container, i.e. as a location.

At the moment namespaces are implemented with dictionaries – but that is a Implementation detail that may change in future versions of Python.

The vars function offers the option of entering the namespace of an object or to look into a class, as it were. The output of the following two print Instructions apply following the code example above. On the reproduction of diverse. We have internal data structures in the namespace for the sake of clarity waived.


When it comes to Python namespaces, some details are noteworthy:

  • The content of namespaces is completely dynamic: you can use both a class as well as a specific object instance at any time to variables or Expand methods as shown at the beginning of this section. You can Even delete variables and methods again with del obj.var!
  • When a new object is created (obj = MyClass ()), then the namespace is the object instance is initially empty! First assignments of self.name = … im Class code or from obj.name = … outside create a new element (a new attribute) in the namespace.
  • If you read obj.xy and Python the attribute in the namespace of the object does not find, it then searches the namespace of the class. Should If you use inheritance, all namespaces of the Searched base classes. Only if the attribute is not in any of these namespaces is found, an error occurs (object has no attribute ‘xxx’).

Python Private class variables

Python lacks a relatively elementary concept that almost all other programming languages ​​do, It goes without saying that there are no private attributes and thus neither private methods still private class variables. It is therefore not possible to use variables or define methods that are only accessible to the code within the class. This limitation is circumvented by two conventions:

  • Attributes whose names begin with an underscore _ are considered private. Who Anytime a class that contains such variables should use them Variables cannot be accessed from outside. (Inside means “code in this context within the class “, i.e. in the indented code block after class Name() :. Outside means “code that uses an object”, e.g. obj.xxx = …)
  • It is a little more effective to prefix attribute names with two underscores. Python then does so called NameMangling and replaces __varname by _classname_ _varname. The variable is therefore better off erroneous Access protected.

As is the case with conventions – you can stick to them or not. The following lines show how easy it is to bypass the protection:

Getter and Setter Methods

Often times when designing a class, you want read and write access to a Check class variables – for example, to a certain range of values to guarantee. In many OOP or  object oriented programming languages, the affected variable declared private. Access is then via a get and a set method. Some programming languages ​​also provide properties for this purpose. In Python, you identify two with the same name in this case Methods with @ varname.setter or with @property. It should be noted that the @property method must be defined first.

In the simplest case, the code for a setter and a getter method looks like this as in the following listing. Every time you run obj.myproperty = …, Python uses the property setter method. With read access Python calls the myproperty getter method. Another example follows in the section “Example: Rectangle Class”.

Operator overloading

Operator overloading allows operators such as +, -, <or> to be assigned new functions, which take effect when the operator is on objects of the respective Class is applied. All you have to do is use the functions provided like add, sub etc. reimplement in your class. A concrete example can be found in the following section.

Example: rectangle class

The following example shows a class for storing rectangles. The setter Methods for the length and width of the rectangle make sure these two Data are always greater than 0. The constructor also uses these methods back. The surface and perimeter methods provide the area and perimeter of the rectangle.

The area used to compare two rectangles is used as a criterion. With the Methods eq, lt and le provide the class code for the operators ==, < and <= available. An implementation of ne, gt and ge for! =,> And> = is not necessary. Python just uses the appropriate methods eq, lt and le and inverts the result. str and repr are used to shape rectangular objects to represent strings.

The following lines show the application of the class. sorted can be a list of Reorder rectangles using the eq, lt and le methods:

Python Inheritance

Thanks to inheritance, you can derive your own classes from other classes. To do this, define your new class as follows:

class MyClass (BasicClass):

This means that all attributes of the basic class are available in MyClass – and of course also all attributes of the classes from which the base class itself was derived. You can use the corresponding methods unchanged or in your re-implement your own class. Python even supports inheritance from several base classes:

class MeineKlasse (BasisKlasse1, BK2, BK3):

In this way, MyClass takes over the attributes of all the basic classes listed. If there are attributes with the same name in several base classes, the attributes in the Inheritance list first named class takes precedence.

In the code of the new class, you can use super() to call methods of a base class,  E.g. with super() .__ init (parameter) __ the constructor of the super class. You only need to use super if you have that method in your have re-implemented their own class and it is not clear for Python without super whether you mean your own method xy or the method xy of the base class.

Classes, Objects, and Instances

This section summarizes some of the special features in Python for the handling of classes and objects. This section is specifically aimed at People who have been dealing with other object-oriented programming languages. They often have more problems understanding than newcomers to Python.

Most OOP object-oriented programming languages ​​have a sharp distinction between classes and objects: classes consist of code, the variable, Attributes, and methods prescribes, so to speak the blueprint for the further Use. Objects, however, are actual instances of these classes, i.e. the actual data. The basic idea is simple: first the class is defined, then objects are created for this class. And of course all of this is in Python as well possible:

In Python, however, the boundaries are less sharp because the class itself is also called Object applies! This object is called the Class Object, as opposed to the Instance Objects. The following example illustrates this concept Class minimalist, which contains no code except pass, so no predefined Attributes / methods. In practice, such ad hoc classes are used quite often used when you want to reproduce simple data structures in an uncomplicated way, i.e. records or structs of other programming languages.

The variable obj1 uses this class as an object! The assignments obj1.a = … and obj1.b = … add two attributes to the class. Instead of obj1 we could also write minimalist directly. obj1 should only clarify the idea here, that the class itself can be used as an object. Behind the scenes obj1 and minimalist are equivalent. Both variables point to the class that is here is used as an object.

Obj2 = minimalist () or the equivalent statement obj2 = obj1 () however a new instance of the class. The round brackets are decisive here, make it clear to Python that we don’t want to just do an assignment, but want to create a new object. This creates a new namespace created. This is initially empty! When reading obj2.a Python recognizes that there is no attribute a in the namespace of the object and takes action therefore back to the underlying class instance. There a has the value 3.

If obj1.a is changed, this change also applies to obj2 and obj3, because there does not yet have its own attribute a. The assignment obj2.b = … now creates a new one Attribute in the namespace of obj2. Attributes in the namespace of an object instance always take precedence over attributes of the underlying class.


Recommended For You

About the Author: Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply