Programowanie obiektowe w Pythonie

W tym samouczku za pomocą przykładów nauczysz się programowania obiektowego (OOP) w języku Python i jego podstawowej koncepcji.

Wideo: Programowanie obiektowe w Pythonie

Programowanie obiektowe

Python to wielo-paradygmatyczny język programowania. Obsługuje różne podejścia do programowania.

Jednym z popularnych podejść do rozwiązania problemu programistycznego jest tworzenie obiektów. Jest to znane jako programowanie obiektowe (OOP).

Obiekt ma dwie cechy:

  • atrybuty
  • zachowanie

Weźmy przykład:

Papuga może być przedmiotem, ponieważ ma następujące właściwości:

  • imię, wiek, kolor jako atrybuty
  • śpiew, taniec jako zachowanie

Koncepcja OOP w Pythonie skupia się na tworzeniu kodu wielokrotnego użytku. Ta koncepcja jest również znana jako DRY (Don't Repeat Yourself).

W Pythonie koncepcja OOP opiera się na kilku podstawowych zasadach:

Klasa

Klasa to plan obiektu.

Możemy myśleć o klasie jak o szkicu papugi z etykietami. Zawiera wszystkie szczegóły dotyczące nazwy, kolorów, rozmiaru itp. Na podstawie tych opisów możemy poznać papugę. Tutaj papuga jest przedmiotem.

Przykładem dla klasy papug może być:

 klasa Papuga: zaliczona

Tutaj używamy classsłowa kluczowego do zdefiniowania pustej klasy Parrot. Z klasy tworzymy instancje. Instancja to określony obiekt utworzony z określonej klasy.

Obiekt

Obiekt (instancja) jest instancją klasy. Gdy zdefiniowana jest klasa, definiowany jest tylko opis obiektu. Dlatego nie jest przydzielana żadna pamięć ani magazyn.

Przykładem obiektu klasy papuga może być:

 obj = Parrot ()

Tutaj obj jest obiektem klasy Parrot.

Załóżmy, że mamy szczegóły dotyczące papug. Teraz pokażemy, jak zbudować klasę i obiekty papug.

Przykład 1: Tworzenie klasy i obiektu w Pythonie

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

Wynik

 Blu to ptak Woo to także ptak Blu ma 10 lat Woo ma 15 lat

W powyższym programie stworzyliśmy klasę o nazwie Parrot. Następnie definiujemy atrybuty. Atrybuty są charakterystyczne dla obiektu.

Te atrybuty są zdefiniowane wewnątrz __init__metody klasy. Jest to metoda inicjowania, która jest uruchamiana po raz pierwszy zaraz po utworzeniu obiektu.

Następnie tworzymy instancje klasy Parrot. Tutaj blu i woo są odniesieniami (wartością) do naszych nowych obiektów.

Możemy uzyskać dostęp do atrybutu klasy za pomocą __class__.species. Atrybuty klasy są takie same dla wszystkich instancji klasy. Podobnie uzyskujemy dostęp do atrybutów instancji za pomocą blu.namei blu.age. Jednak atrybuty instancji są różne dla każdej instancji klasy.

Aby dowiedzieć się więcej o klasach i obiektach, przejdź do sekcji Klasy i obiekty języka Python

Metody

Metody to funkcje zdefiniowane w treści klasy. Służą do definiowania zachowań obiektu.

Przykład 2: Tworzenie metod w Pythonie

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

Wynik

 Blu śpiewa „Happy” Blu teraz tańczy

W powyższym programie, możemy definiować na dwa sposoby tj sing()a dance(). Nazywane są one metodami instancji, ponieważ są wywoływane w obiekcie instancji, tj blu.

Dziedzictwo

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.

Aby użyć polimorfizmu, stworzyliśmy wspólny interfejs, czyli flying_test()funkcję, która pobiera dowolny obiekt i wywołuje fly()metodę obiektu . Tak więc, kiedy w funkcji minęliśmy obiekty niebieskie i peggy flying_test(), działała skutecznie.

Kluczowe kwestie do zapamiętania:

  • Programowanie zorientowane obiektowo sprawia, że ​​program jest łatwy do zrozumienia i efektywny.
  • Ponieważ klasa jest współdzielona, ​​kod można ponownie wykorzystać.
  • Dane są bezpieczne dzięki abstrakcji.
  • Polimorfizm umożliwia korzystanie z tego samego interfejsu dla różnych obiektów, więc programiści mogą pisać wydajny kod.

Interesujące artykuły...