Anatomia klasy: atrybuty i metody

Wprowadzenie do programowania obiektowego w Pythonie

George Boorman

Curriculum Manager, DataCamp

Klasa Customer

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ę
c_one = Customer()
c_two = Customer()
  • Użyj ClassName(), aby utworzyć obiekt klasy ClassName
Wprowadzenie do programowania obiektowego 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 pierwszego argumentu w definicji metody
cust = Customer()
cust.identify("Laura")
I am Customer Laura
  • Pomiń self podczas wywoływania metody na obiekcie
Wprowadzenie do programowania obiektowego w Pythonie
class Customer:  
    def identify(self, name):
        print("I am Customer " + name)

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

Czym jest self?

  • Klasy są szablonami
  • self powinien być pierwszym argumentem każdej metody
  • self jest zastępnikiem (jeszcze nieistniejącego) obiektu
  • cust.identify("Laura") zostanie zinterpretowane jako Customer.identify(cust, "Laura")
Wprowadzenie do programowania obiektowego w Pythonie

Potrzebujemy atrybutów

  • OOP łączy dane z metodami operującymi na tych danych
    • Imię obiektu Customer powinno być atrybutem

 

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

Wprowadzenie do programowania obiektowego 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 # Will create .name when set_name is called self.name = new_name
# Create an object # .name doesn't exist here yet cust = Customer()
# .name is created and set to "Lara de Silva" cust.set_name("Lara de Silva")
print(cust.name)
Lara de Silva
Wprowadzenie do programowania obiektowego 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
Wprowadzenie do programowania obiektowego w Pythonie

Czas na ćwiczenia!

Wprowadzenie do programowania obiektowego w Pythonie

Preparing Video For Download...