Šajā apmācībā jūs uzzināsit par objektu orientētu programmēšanu (OOP) Python un tās pamatjēdzienu, izmantojot piemērus.
Video: objektorientēta programmēšana Python
Uz objektu orientēta programmēšana
Python ir daudzparadigmas programmēšanas valoda. Tas atbalsta dažādas programmēšanas pieejas.
Viena no populārākajām pieejām programmēšanas problēmas risināšanai ir objektu izveidošana. Tas ir pazīstams kā uz objektu orientēta programmēšana (OOP).
Objektam ir divas īpašības:
- atribūti
- uzvedība
Ņemsim piemēru:
Papagailis var būt objekts, jo tam ir šādas īpašības:
- nosaukums, vecums, krāsa kā atribūti
- dziedāšana, dejošana kā uzvedība
OOP jēdziens Python ir vērsts uz atkārtoti izmantojama koda izveidi. Šis jēdziens ir pazīstams arī kā DRY (neatkārtojiet sevi).
Programmā Python OOP jēdziens atbilst dažiem pamatprincipiem:
Klase
Klase ir objekta projekts.
Mēs varam uzskatīt klasi par papagaiļa skici ar etiķetēm. Tajā ir visa informācija par nosaukumu, krāsām, izmēru utt. Pamatojoties uz šiem aprakstiem, mēs varam izpētīt papagaili. Šeit papagailis ir objekts.
Papagaiļa klases piemērs var būt:
klase Papagailis: caurlaide
Šeit mēs izmantojam class
atslēgvārdu, lai definētu tukšu klasi Papagailis. No klases mēs konstruējam gadījumus. Eksemplārs ir īpašs objekts, kas izveidots no noteiktas klases.
Objekts
Objekts (eksemplārs) ir klases eksemplārs. Kad klase ir definēta, tiek definēts tikai objekta apraksts. Tāpēc netiek piešķirta atmiņa vai krātuve.
Papagaiļu klases objekta piemērs var būt:
obj = Papagailis ()
Šeit obj ir klases objekts Parrot
.
Pieņemsim, ka mums ir informācija par papagaiļiem. Tagad mēs parādīsim, kā veidot papagaiļu klasi un priekšmetus.
1. piemērs: klases un objekta izveide 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))
Rezultāts
Blu ir putns Woo ir arī putns Blu ir 10 gadus vecs Woo ir 15 gadus vecs
Iepriekš minētajā programmā mēs izveidojām klasi ar nosaukumu Parrot. Tad mēs definējam atribūtus. Atribūti ir objekta raksturojums.
Šie atribūti ir definēti __init__
klases metodē. Tā ir inicializētāja metode, kas vispirms tiek palaista, tiklīdz objekts ir izveidots.
Pēc tam mēs izveidojam Parrot klases gadījumus. Šeit blu un woo ir atsauces (vērtība) uz mūsu jaunajiem objektiem.
Mēs varam piekļūt klases atribūtam, izmantojot __class__.species
. Klases atribūti visiem klases gadījumiem ir vienādi. Līdzīgi mēs piekļūstam instances atribūtiem, izmantojot blu.name
un blu.age
. Tomēr gadījumu piemēri katram klases gadījumam ir atšķirīgi.
Lai uzzinātu vairāk par klasēm un objektiem, dodieties uz lapu Python klases un objekti
Metodes
Metodes ir funkcijas, kas noteiktas klases ķermenī. Tos izmanto, lai definētu objekta uzvedību.
2. piemērs: metožu izveide 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())
Rezultāts
Blu dzied “Happy” Blu tagad dejo
Iepriekš minētajā programmā mēs definējam divas metodes, ti, sing()
un dance()
. Tās sauc par instances metodēm, jo tās tiek izsauktas uz instances objektu, ti blu
.
Mantojums
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.
Lai izmantotu polimorfismu, mēs izveidojām kopēju saskarni, ti, flying_test()
funkciju, kas ņem jebkuru objektu un izsauc objekta fly()
metodi. Tādējādi, kad mēs garām funkciju blu un peggy objektiem flying_test()
, tā darbojās efektīvi.
Galvenie jautājumi, kas jāatceras:
- Uz objektu orientēta programmēšana padara programmu viegli saprotamu, kā arī efektīvu.
- Tā kā klase ir koplietojama, kodu var izmantot atkārtoti.
- Dati ir droši un droši, izmantojot datus.
- Polimorfisms pieļauj vienu un to pašu saskarni dažādiem objektiem, tāpēc programmētāji var rakstīt efektīvu kodu.