Python-objektorienterad programmering

I den här handledningen lär du dig om objektorienterad programmering (OOP) i Python och dess grundläggande koncept med hjälp av exempel.

Video: Objektorienterad programmering i Python

Objektorienterad programmering

Python är ett programmeringsspråk med flera paradigmer. Den stöder olika programmeringsmetoder.

En av de populära metoderna för att lösa ett programmeringsproblem är att skapa objekt. Detta är känt som Object-Oriented Programming (OOP).

Ett objekt har två egenskaper:

  • attribut
  • beteende

Låt oss ta ett exempel:

En papegoja är kan vara ett objekt, eftersom den har följande egenskaper:

  • namn, ålder, färg som attribut
  • sång, dans som beteende

Begreppet OOP i Python fokuserar på att skapa återanvändbar kod. Detta koncept är också känt som DRY (Don't Repeat Yourself).

I Python följer begreppet OOP några grundläggande principer:

Klass

En klass är en ritning för objektet.

Vi kan tänka på klassen som en skiss av en papegoja med etiketter. Den innehåller alla detaljer om namn, färger, storlek etc. Baserat på dessa beskrivningar kan vi studera om papegojan. Här är en papegoja ett objekt.

Exemplet för papegojklass kan vara:

 klass papegoja: pass

Här använder vi classnyckelordet för att definiera en tom klass papegoja. Från klassen konstruerar vi instanser. En instans är ett specifikt objekt som skapats från en viss klass.

Objekt

Ett objekt (instans) är en instantiering av en klass. När klass definieras definieras endast beskrivningen för objektet. Därför tilldelas inget minne eller lagring.

Exemplet för objekt av papegojklass kan vara:

 obj = papegoja ()

Här är obj ett klassobjekt Parrot.

Antag att vi har detaljer om papegojor. Nu ska vi visa hur man bygger papegojornas klass och objekt.

Exempel 1: Skapa klass och objekt i 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))

Produktion

 Blu är en fågel Woo är också en fågel Blu är 10 år gammal Woo är 15 år gammal

I ovanstående program skapade vi en klass med namnet Parrot. Sedan definierar vi attribut. Attributen är en egenskap hos ett objekt.

Dessa attribut definieras __init__i klassens metod. Det är initialiseringsmetoden som körs så snart objektet skapas.

Sedan skapar vi instanser av Parrot-klassen. Här är blu och woo referenser (värde) till våra nya objekt.

We can access the class attribute using __class__.species. Class attributes are the same for all instances of a class. Similarly, we access the instance attributes using blu.name and blu.age. However, instance attributes are different for every instance of a class.

To learn more about classes and objects, go to Python Classes and Objects

Methods

Methods are functions defined inside the body of a class. They are used to define the behaviors of an object.

Example 2 : Creating Methods 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())

Output

 Blu sings 'Happy' Blu is now dancing

In the above program, we define two methods i.e sing() and dance(). These are called instance methods because they are called on an instance object i.e blu.

Inheritance

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.

För att använda polymorfism skapade vi ett gemensamt gränssnitt, dvs flying_test()funktion som tar alla objekt och kallar objektets fly()metod. Således, när vi passerade de blå och peggy föremålen i flying_test()funktionen, körde den effektivt.

Viktiga punkter att komma ihåg:

  • Objektorienterad programmering gör programmet lätt att förstå såväl som effektivt.
  • Eftersom klassen kan delas kan koden återanvändas.
  • Data är säker och säker med dataabstraktion.
  • Polymorfism tillåter samma gränssnitt för olika objekt, så att programmerare kan skriva effektiv kod.

Intressanta artiklar...