Python objektno usmerjeno programiranje

V tej vadnici boste s pomočjo primerov spoznali objektno usmerjeno programiranje (OOP) v Pythonu in njegov temeljni koncept.

Video: Objektno usmerjeno programiranje v Pythonu

Objektno usmerjeno programiranje

Python je programski jezik z več paradigmami. Podpira različne programske pristope.

Eden izmed priljubljenih pristopov k reševanju programskega problema je ustvarjanje predmetov. To je znano kot objektno usmerjeno programiranje (OOP).

Predmet ima dve značilnosti:

  • lastnosti
  • vedenje

Vzemimo primer:

Papagaj je lahko predmet, saj ima naslednje lastnosti:

  • ime, starost, barva kot atributi
  • petje, ples kot vedenje

Koncept OOP v Pythonu se osredotoča na ustvarjanje kode za večkratno uporabo. Ta koncept je znan tudi kot SUHO (Ne ponavljajte se).

V Pythonu koncept OOP sledi nekaterim osnovnim načelom:

Razred

Razred je načrt predmeta.

Razred si lahko predstavljamo kot skico papige z nalepkami. Vsebuje vse podrobnosti o imenu, barvah, velikosti itd. Na podlagi teh opisov lahko preučujemo papigo. Tu je papiga predmet.

Primer za razred papige je lahko:

 razred Papagaj: mimo

Tu uporabljamo classključno besedo za določitev praznega razreda Parrot. Iz razreda gradimo primerke. Primerek je določen objekt, ustvarjen iz določenega razreda.

Predmet

Objekt (primerek) je primer razreda. Ko je razred definiran, je definiran samo opis predmeta. Zato ni dodeljenega pomnilnika ali pomnilnika.

Primer predmeta papagajskega razreda je lahko:

 obj = Papiga ()

Tu je obj predmet razreda Parrot.

Recimo, da imamo podrobnosti o papagajih. Zdaj bomo pokazali, kako zgraditi razred in predmete papige.

Primer 1: Ustvarjanje razreda in predmeta v Pythonu

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

Izhod

 Blu je ptica Woo je tudi ptica Blu je stara 10 let Woo je stara 15 let

V zgornjem programu smo ustvarili razred z imenom Parrot. Nato definiramo atribute. Atributi so značilnost predmeta.

Ti atributi so definirani znotraj __init__metode razreda. Metoda inicializacije se najprej zažene takoj, ko je objekt ustvarjen.

Nato izdelamo primerke razreda Parrot. Tu sta blu in woo referenca (vrednost) na naše nove predmete.

Do atributa razreda lahko dostopamo z uporabo __class__.species. Atributi razreda so enaki za vse primerke razreda. Podobno dostopamo do atributov primerka z uporabo blu.namein blu.age. Atributi primerka pa se za vsak primerek razreda razlikujejo.

Če želite izvedeti več o razredih in predmetih, pojdite na razrede in predmete Python

Metode

Metode so funkcije, definirane znotraj telesa razreda. Uporabljajo se za določanje vedenja predmeta.

Primer 2: Ustvarjanje metod v Pythonu

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

Izhod

 Blu poje "Happy" Blu zdaj pleše

V zgornjem programu definiramo dve metodi, tj. sing()In dance(). Te se imenujejo metode primerkov, ker so poklicane na primerku predmeta, tj blu.

Dedovanje

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.

Za uporabo polimorfizma smo ustvarili skupni vmesnik, tj. flying_test()Funkcijo, ki zavzame kateri koli predmet in pokliče fly()metodo predmeta . Ko smo torej v flying_test()funkciji podali modre in peggi predmete , je tekla učinkovito.

Ključne točke, ki si jih je treba zapomniti:

  • Z objektno usmerjenim programiranjem je program enostaven za razumevanje in tudi učinkovit.
  • Ker je razred primeren za skupno rabo, lahko kodo ponovno uporabimo.
  • Podatki so varni in varni z abstrakcijo podatkov.
  • Polimorfizem omogoča enak vmesnik za različne predmete, zato lahko programerji pišejo učinkovito kodo.

Zanimive Članki...