Anatomia klasy: atrybuty i metody

Programowanie obiektowe w Pythonie

Alex Yarosh

Content Quality Analyst @ DataCamp

Podstawowa klasa

class Customer:

# code for class goes here
pass
  • class <name>: rozpoczyna definicję klasy
  • kod wewnątrz class jest wcięty
  • użyj pass, aby utworzyć „pustą" klasę
c1 = Customer()
c2 = Customer()
  • użyj ClassName(), aby utworzyć obiekt klasy ClassName
Programowanie obiektowe w Pythonie

Dodawanie metod do klasy

class Customer:  

    def identify(self, name):   
      print("I am Customer " + name)
  • definicja metody = definicja funkcji wewnątrz klasy
  • użyj self jako 1. argumentu w definicji metody
cust = Customer()
cust.identify("Laura")
I am Customer Laura
  • pomiń self podczas wywoływania metody na obiekcie
Programowanie obiektowe w Pythonie
class Customer:  

    def identify(self, name):   
      print("I am Customer " + name)

cust = Customer()
cust.identify("Laura")

Czym jest self?

  • klasy są szablonami – jak odwołać się do danych konkretnego obiektu?
  • self to zastępnik konkretnego obiektu używany w definicji klasy
  • powinien być pierwszym argumentem każdej metody
  • Python obsługuje self automatycznie przy wywołaniu metody na obiekcie:

cust.identify("Laura") jest interpretowane jako Customer.identify(cust, "Laura")

Programowanie obiektowe w Pythonie

Potrzebujemy atrybutów

  • Enkapsulacja: łączenie danych z metodami, które na nich operują
  • Np. imię obiektu Customer powinno być atrybutem

  $$\text{\Large{Atrybuty tworzy się przez przypisanie (=) w metodach}}$$

Programowanie obiektowe w Pythonie

Dodawanie atrybutu do klasy

class Customer:  
    # set the name attribute of an object to new_name
    def set_name(self, new_name):

# Create an attribute by assigning a value self.name = new_name # <-- will create .name when set_name is called
cust = Customer()                   # <--.name doesn't exist here yet

cust.set_name("Lara de Silva") # <--.name is created and set to "Lara de Silva"
print(cust.name) # <--.name can be used
Lara de Silva
Programowanie obiektowe w Pythonie

Stara wersja

class Customer:  



    # Using a parameter
    def identify(self, name):   
      print("I am Customer" + name)
cust = Customer()

cust.identify("Eris Odoro")
I am Customer Eris Odoro

Nowa wersja

class Customer:  
   def set_name(self, new_name): 
      self.name = new_name

    # Using .name from the object it*self*
    def identify(self):     
      print("I am Customer" + self.name)
cust = Customer()
cust.set_name("Rashid Volkov")
cust.identify()
I am Customer Rashid Volkov
Programowanie obiektowe w Pythonie

Czas na ćwiczenia!

Programowanie obiektowe w Pythonie

Preparing Video For Download...