Objektovo orientované programovanie v jazyku Python

V tomto výučbe sa pomocou príkladov dozviete o objektovo orientovanom programovaní (OOP) v Pythone a jeho základnom koncepte.

Video: Objektovo orientované programovanie v Pythone

Objektovo orientované programovanie

Python je programovací jazyk s viacerými paradigmami. Podporuje rôzne programovacie prístupy.

Jedným z populárnych prístupov k riešeniu programovacieho problému je vytváranie objektov. Toto je známe ako objektovo orientované programovanie (OOP).

Objekt má dve charakteristiky:

  • atribúty
  • správanie

Uveďme si príklad:

Papagáj môže byť objekt, pretože má nasledujúce vlastnosti:

  • meno, vek, farba ako atribúty
  • spev, tanec ako správanie

Koncept OOP v Pythone sa zameriava na vytvorenie opakovane použiteľného kódu. Tento koncept je tiež známy ako DRY (Don't Repeat Yourself).

V Pythone sa koncept OOP riadi niektorými základnými princípmi:

Trieda

Trieda je návrhom objektu.

Triedu si môžeme predstaviť ako náčrt papagája so štítkami. Obsahuje všetky podrobnosti o mene, farbách, veľkosti atď. Na základe týchto popisov môžeme študovať papagája. Tu je papagáj predmetom.

Príkladom pre triedu papagája môže byť:

 trieda Papagáj: pas

Tu používame classkľúčové slovo na definovanie prázdnej triedy Parrot. Z triedy zostavujeme inštancie. Inštancia je špecifický objekt vytvorený z konkrétnej triedy.

Objekt

Objekt (inštancia) je inštanciou triedy. Keď je definovaná trieda, je definovaný iba popis objektu. Preto nie je pridelená žiadna pamäť alebo úložisko.

Príkladom objektu triedy papagájov môže byť:

 obj = papagáj ()

Tu je obj objekt triedy Parrot.

Predpokladajme, že máme podrobnosti o papagájoch. Teraz si ukážeme, ako zostaviť triedu a objekty papagájov.

Príklad 1: Vytvorenie triedy a objektu v Pythone

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

Výkon

 Blu je vták Woo je tiež vták Blu má 10 rokov Woo má 15 rokov

Vo vyššie uvedenom programe sme vytvorili triedu s názvom Papagáj. Potom definujeme atribúty. Atribúty sú charakteristikou objektu.

Tieto atribúty sú definované vo vnútri __init__metódy triedy. Je to metóda inicializátora, ktorá sa najskôr spustí hneď po vytvorení objektu.

Potom vytvoríme inštancie triedy Parrot. Tu sú blu a woo odkazy (hodnota) na naše nové objekty.

K atribútu triedy môžeme pristupovať pomocou __class__.species. Atribúty triedy sú rovnaké pre všetky inštancie triedy. Podobne pristupujeme k atribútom inštancie pomocou blu.namea blu.age. Atribúty inštancie sú však odlišné pre každú inštanciu triedy.

Ak sa chcete dozvedieť viac informácií o triedach a objektoch, prejdite na stránku Python Classes and Objects

Metódy

Metódy sú funkcie definované vo vnútri triedy. Používajú sa na definovanie správania objektu.

Príklad 2: Vytváranie metód v Pythone

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

Výkon

 Blu spieva „Happy“ Blu teraz tancuje

Vo vyššie uvedenom programe definujeme dve metódy tj sing()a dance(). Nazývajú sa inštančné metódy, pretože sa volajú na inštančnom objekte, tj blu.

Dedenie

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.

Pre použitie polymorfizmu sme vytvorili spoločné rozhranie, tj. flying_test()Funkciu, ktorá berie akýkoľvek objekt a volá fly()metódu objektu . Keď sme teda vo flying_test()funkcii prešli cez objekty blu a peggy, fungovalo to efektívne.

Kľúčové body, ktoré si treba pamätať:

  • Objektovo orientované programovanie umožňuje ľahko pochopiteľný a efektívny program.
  • Pretože triedu je možné zdieľať, je možné kód znova použiť.
  • Dáta sú v bezpečí a zabezpečené pomocou abstrakcie údajov.
  • Polymorfizmus umožňuje rovnaké rozhranie pre rôzne objekty, takže programátori môžu písať efektívny kód.

Zaujímavé články...