Python Objektorientierte Programmierung

In diesem Tutorial lernen Sie anhand von Beispielen die objektorientierte Programmierung (OOP) in Python und ihr grundlegendes Konzept kennen.

Video: Objektorientierte Programmierung in Python

Objekt orientierte Programmierung

Python ist eine Multi-Paradigma-Programmiersprache. Es unterstützt verschiedene Programmieransätze.

Einer der gängigen Ansätze zur Lösung eines Programmierproblems ist das Erstellen von Objekten. Dies wird als objektorientierte Programmierung (OOP) bezeichnet.

Ein Objekt hat zwei Eigenschaften:

  • Attribute
  • Verhalten

Nehmen wir ein Beispiel:

Ein Papagei kann ein Objekt sein, da er die folgenden Eigenschaften hat:

  • Name, Alter, Farbe als Attribute
  • singen, tanzen als Verhalten

Das Konzept von OOP in Python konzentriert sich auf die Erstellung von wiederverwendbarem Code. Dieses Konzept wird auch als DRY (Don't Repeat Yourself) bezeichnet.

In Python folgt das Konzept von OOP einigen Grundprinzipien:

Klasse

Eine Klasse ist eine Blaupause für das Objekt.

Wir können uns Klasse als eine Skizze eines Papageis mit Etiketten vorstellen. Es enthält alle Details zu Name, Farben, Größe usw. Anhand dieser Beschreibungen können wir den Papagei untersuchen. Hier ist ein Papagei ein Objekt.

Das Beispiel für eine Papageienklasse kann sein:

 Klasse Papagei: bestanden

Hier verwenden wir das classSchlüsselwort, um eine leere Klasse Parrot zu definieren. Aus der Klasse konstruieren wir Instanzen. Eine Instanz ist ein bestimmtes Objekt, das aus einer bestimmten Klasse erstellt wurde.

Objekt

Ein Objekt (eine Instanz) ist eine Instanziierung einer Klasse. Wenn eine Klasse definiert ist, wird nur die Beschreibung für das Objekt definiert. Daher wird kein Speicher oder Speicher zugewiesen.

Das Beispiel für ein Objekt der Papageienklasse kann sein:

 obj = Papagei ()

Hier ist obj ein Objekt der Klasse Parrot.

Angenommen, wir haben Details zu Papageien. Jetzt werden wir zeigen, wie man die Klasse und Objekte von Papageien baut.

Beispiel 1: Erstellen von Klassen und Objekten in Python

 class Parrot: # class attribute species = "bird" # instance attribute def __init__(self, name, age): self.name = name self.age = age # instantiate the Parrot class blu = Parrot("Blu", 10) woo = Parrot("Woo", 15) # access the class attributes print("Blu is a ()".format(blu.__class__.species)) print("Woo is also a ()".format(woo.__class__.species)) # access the instance attributes print("() is () years old".format( blu.name, blu.age)) print("() is () years old".format( woo.name, woo.age))

Ausgabe

 Blu ist ein Vogel Woo ist auch ein Vogel Blu ist 10 Jahre alt Woo ist 15 Jahre alt

Im obigen Programm haben wir eine Klasse mit dem Namen Parrot erstellt. Dann definieren wir Attribute. Die Attribute sind ein Merkmal eines Objekts.

Diese Attribute werden innerhalb der __init__Methode der Klasse definiert. Dies ist die Initialisierungsmethode, die zum ersten Mal ausgeführt wird, sobald das Objekt erstellt wird.

Dann erstellen wir Instanzen der Parrot-Klasse. Hier sind Blu und Woo Verweise (Wert) auf unsere neuen Objekte.

Wir können mit auf das Klassenattribut zugreifen __class__.species. Klassenattribute sind für alle Instanzen einer Klasse gleich. Ebenso greifen wir mit blu.nameund auf die Instanzattribute zu blu.age. Die Instanzattribute sind jedoch für jede Instanz einer Klasse unterschiedlich.

Weitere Informationen zu Klassen und Objekten finden Sie unter Python-Klassen und -Objekte

Methoden

Methoden sind Funktionen, die im Hauptteil einer Klasse definiert sind. Sie werden verwendet, um das Verhalten eines Objekts zu definieren.

Beispiel 2: Erstellen von Methoden in Python

 class Parrot: # instance attributes def __init__(self, name, age): self.name = name self.age = age # instance method def sing(self, song): return "() sings ()".format(self.name, song) def dance(self): return "() is now dancing".format(self.name) # instantiate the object blu = Parrot("Blu", 10) # call our instance methods print(blu.sing("'Happy'")) print(blu.dance())

Ausgabe

 Blu singt 'Happy' Blu tanzt jetzt

Im obigen Programm definieren wir zwei Methoden, nämlich sing()und dance(). Diese werden als Instanzmethoden bezeichnet, da sie für ein Instanzobjekt aufgerufen werden, d blu. H.

Erbe

Inheritance is a way of creating a new class for using details of an existing class without modifying it. The newly formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent class).

Example 3: Use of Inheritance in Python

 # parent class class Bird: def __init__(self): print("Bird is ready") def whoisThis(self): print("Bird") def swim(self): print("Swim faster") # child class class Penguin(Bird): def __init__(self): # call super() function super().__init__() print("Penguin is ready") def whoisThis(self): print("Penguin") def run(self): print("Run faster") peggy = Penguin() peggy.whoisThis() peggy.swim() peggy.run()

Output

 Bird is ready Penguin is ready Penguin Swim faster Run faster

In the above program, we created two classes i.e. Bird (parent class) and Penguin (child class). The child class inherits the functions of parent class. We can see this from the swim() method.

Again, the child class modified the behavior of the parent class. We can see this from the whoisThis() method. Furthermore, we extend the functions of the parent class, by creating a new run() method.

Additionally, we use the super() function inside the __init__() method. This allows us to run the __init__() method of the parent class inside the child class.

Encapsulation

Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct modification which is called encapsulation. In Python, we denote private attributes using underscore as the prefix i.e single _ or double __.

Example 4: Data Encapsulation in Python

 class Computer: def __init__(self): self.__maxprice = 900 def sell(self): print("Selling Price: ()".format(self.__maxprice)) def setMaxPrice(self, price): self.__maxprice = price c = Computer() c.sell() # change the price c.__maxprice = 1000 c.sell() # using setter function c.setMaxPrice(1000) c.sell()

Output

 Selling Price: 900 Selling Price: 900 Selling Price: 1000

In the above program, we defined a Computer class.

We used __init__() method to store the maximum selling price of Computer. We tried to modify the price. However, we can't change it because Python treats the __maxprice as private attributes.

As shown, to change the value, we have to use a setter function i.e setMaxPrice() which takes price as a parameter.

Polymorphism

Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).

Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle). However we could use the same method to color any shape. This concept is called Polymorphism.

Example 5: Using Polymorphism in Python

 class Parrot: def fly(self): print("Parrot can fly") def swim(self): print("Parrot can't swim") class Penguin: def fly(self): print("Penguin can't fly") def swim(self): print("Penguin can swim") # common interface def flying_test(bird): bird.fly() #instantiate objects blu = Parrot() peggy = Penguin() # passing the object flying_test(blu) flying_test(peggy)

Output

 Parrot can fly Penguin can't fly

In the above program, we defined two classes Parrot and Penguin. Each of them have a common fly() method. However, their functions are different.

Um den Polymorphismus zu verwenden, haben wir eine gemeinsame Schnittstelle erstellt, dh eine flying_test()Funktion, die jedes Objekt aufnimmt und die fly()Methode des Objekts aufruft . Als wir also die Blu- und Peggy-Objekte in der flying_test()Funktion übergeben haben, lief es effektiv.

Wichtige Punkte, die Sie beachten sollten:

  • Die objektorientierte Programmierung macht das Programm leicht verständlich und effizient.
  • Da die Klasse gemeinsam genutzt werden kann, kann der Code wiederverwendet werden.
  • Daten sind mit Datenabstraktion sicher und geschützt.
  • Der Polymorphismus ermöglicht dieselbe Schnittstelle für verschiedene Objekte, sodass Programmierer effizienten Code schreiben können.

Interessante Beiträge...