Python Programming

OOP In Python: Object Oriented Programming Python with Examples

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:

s1 = 'Object Oriented Features of Python'

s2 = s1. lower()

print (s2) # object-oriented features of python

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:

# Use objects and classes

var = a class ()

var. an attribute = 123

result = var.onemethod (17)

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.

# Definition of a class

class MyClass:

code ...

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:

class MyClass:

def method (self, x, y):

self. data = x + y

...

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

obj = MyClass ()

obj. method (127, 234)

Myclass . method (obj, 127, 234) # equivalent code




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 (…).

class MyClass:

def method (x, y):

return x + y

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).

#! / usr / bin / python3

class MyClass:

@staticmethod

def method (x, y):

return x + y

# that's by design

print (MyClass. method (1, 2)) # Issue 3

# but that's how it works now

obj = MyClass ()

print (obj.method (1, 2)) # output 3

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.

#! / usr / bin / python3

class MyClass:

def __init__ (self, a, b):

self .a = a

self .b = b

obj = MyClass (1, 2)

obj.c = 3

print (obj .a, obj .b, obj .c) # output 1 2 3


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:

obj = MyClass ()

obj. new variable = 23 # new variable for obj

def f (x): return (2 * x)

MyClass .f = f # new function for MyClass

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:

#! / usr / bin / python3

class MyClass ():

var = 3

def method (self, p1):

self. var = p1

obj = MyClass ()

print (obj. var) # output 3

obj. var = 4;

print (obj. var) # output 4

obj. method (5)

print (obj. var) # output 5



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.

print (vars (MyClass))

# Output {'var': 3, 'method': <function MyClass. method

# at 0 x1007e5200>, ...}

print (vars (obj)) # output {'var': 5}

 

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:

#! / usr / bin / python3

class Test ():

_private = 1

__ still private = 2

obj = test ()

print (obj. _privat) # Issue 1

print (obj. _Test__nochPrivater) # Issue 2



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”.

# Class with getter / setter for 'my property'

class MyClass:

# Getter - method for myproperty

@property

def myproperty (self):

return self. __myproperty

# Setter method for my property

@myproperty. setter

def myproperty (self, value):

self. __myproperty = worth

# Using the class

obj = MyClass ()

obj. myproperty = 1

print (obj. myproperty)

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.

#! / usr / bin / python3

# Rectangle class

class rectangle ():

# Constructor

def __init__ (self, length, width):

self. length = length

self. width = width

# Getters and Setters for length

@property

def length (self):

return self. __length

@length. setter

def length (self, length):

if length> 0:

self. __length = length

else:

raise ValueError ('The length must be greater than 0.')

# Getters and Setters for width

@property

def width (self):

return self. __width

@width. setter

def width (self, width):

if width> 0:

self. __width = width

else:

raise ValueError ('The width must be greater than 0.')

# Methods for perimeter and area

def scope (self):

return (self. __ length + self. __ width) * 2

def area (self):

return self. __ length * self. __width

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.

# Continuation of the class code of the rectangle class

# Operator overloading for <,>, <=,> =, == and! =

def __eq__ (self, other):

return self. area () == other. area ()

def __lt__ (self, other):

return self. area () <other. area ()

def __le__ (self, other):

return self. area () <= other. area ()

# Conversion to strings

def __str__ (self):

return 'R (% .1f,%. 1 f)'% (self. length, self. width)

# for output by print

def __repr__ (self):

return 'R (% .1f,%. 1 f)'% (self. length, self. width)



The following lines show the application of the class. sorted can be a list of Reorder rectangles using the __eq__, __lt__ and __le__ methods:

# Application of the class

r1 = rectangle (2, 4)

r2 = rectangle (7, 12)

print (r1. flaeche (), r2. flaeche ()) # Issue 8, 84

if r2> r1:

print ("The area of ​​r2 is larger than that of r1.")

l = [r2, r1, rectangle (4, 4)]

print (sorted (l))

# Output [R (2.0, 4.0), R (4.0, 4.0), R (7.0, 12.0)]

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:

class MyClass:

code ...

obj1 = MyClass () # three instances (objects)

obj2 = MyClass () # of myClass

obj3 = MyClass ()

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.

#! / usr / bin / python3

class minimalist: pass

obj1 = Minimalist # obj1 and Minimalist are 'Class Objects'

obj1 .a = 3

obj1 .b = 4

obj2 = Minimalist () # obj2 and obj3 are two of each other

obj3 = Minimalist () # independent 'Instance Objects'

obj2 .c = 5

obj3 .c = 6

# Attributes in the namespaces of the class and the

# both instances

print (vars (obj1)) # output {'a': 3, 'b': 4, ...}

print (vars (obj2)) # {'c': 5}

print (vars (obj3)) # {'c': 6}

print (obj1 .a, obj2 .a, obj3 .a) # output 3 3 3

print (obj1 .b, obj2 .b, obj3 .b) # output 4 4 4

print (obj2 .c, obj3 .c) # output 5 6

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.

# Continuation

obj1 .a = 7

print (obj1 .a, obj2 .a, obj3 .a) # output 7 7 7

obj2 .b = 8

print (obj1 .b, obj2 .b, obj3 .b) # output 4 8 4

If now obj1.b is changed, the change naturally applies to obj1 and also to obj3,

because there is no attribute b in its namespace. obj2.b remains 8. The assignment

obj2.c = ... proves that the attributes in the namespaces of object instances

are independent of each other.

# Continuation

obj1 .b = 9

print (obj1 .b, obj2 .b, obj3 .b) # output 9 8 9

obj2 .c = 10

print (obj2 .c, obj3 .c) # output 10 6

print (vars (obj1)) # output {'a': 7, 'b': 9, ...}

print (vars (obj2)) # {'b': 8, 'c': 10,}

print (vars (obj3)) # {'c': 6}

 

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

Your email address will not be published. Required fields are marked *

Back to top button