Anatomie třídy: atributy a metody

Object-Oriented Programming in Python

Alex Yarosh

Content Quality Analyst @ DataCamp

Základní třída

class Customer:

# code for class goes here
pass
  • class <name>: zahájí definici třídy
  • kód uvnitř class je odsazen
  • pomocí pass vytvoříme „prázdnou" třídu
c1 = Customer()
c2 = Customer()
  • pomocí ClassName() vytvoříme objekt třídy ClassName
Object-Oriented Programming in Python

Přidání metod do třídy

class Customer:  

    def identify(self, name):   
      print("I am Customer " + name)
  • definice metody = definice funkce uvnitř třídy
  • jako 1. argument definice metody použijte self
cust = Customer()
cust.identify("Laura")
I am Customer Laura
  • při volání metody na objektu self ignorujte
Object-Oriented Programming in Python
class Customer:  

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

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

Co je self?

  • třídy jsou šablony – jak odkazovat na data konkrétního objektu?
  • self zastupuje konkrétní objekt v definici třídy
  • měl by být prvním argumentem každé metody
  • Python se o self postará při volání metody z objektu:

cust.identify("Laura") bude interpretováno jako Customer.identify(cust, "Laura")

Object-Oriented Programming in Python

Potřebujeme atributy

  • Zapouzdření: sdružení dat s metodami, které s nimi pracují
  • Např. jméno zákazníka Customer by mělo být atributem

  $$\text{\Large{Atributy se vytvářejí přiřazením (=) v metodách}}$$

Object-Oriented Programming in Python

Přidání atributu do třídy

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
Object-Oriented Programming in Python

Stará verze

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

Nová verze

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
Object-Oriented Programming in Python

Pojďme si procvičit!

Object-Oriented Programming in Python

Preparing Video For Download...