Úvod do objektově orientovaného programování v Pythonu
George Boorman
Curriculum Manager, DataCamp
class Customer:# Code for class goes herepass
class <name>: zahajuje definici třídyclass je odsazenýpass pro vytvoření „prázdné“ třídyc_one = Customer()
c_two = Customer()
ClassName() vytvoříš objekt třídy ClassNameclass Customer:def identify(self, name): print("I am Customer " + name)
self jako první argument v definici metodycust = Customer()
cust.identify("Laura")
I am Customer Laura
self ignorujclass Customer:
def identify(self, name):
print("I am Customer " + name)
cust = Customer()
cust.identify("Laura")
self by měl být první argument každé metodyself zastupuje (zatím nevytvořený) objektcust.identify("Laura") se interpretuje jako Customer.identify(cust, "Laura")Customer by mělo být atribut
$$\text{\Large{Atributy se vytvářejí přiřazením (=) v metodách}}$$
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
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
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
Úvod do objektově orientovaného programování v Pythonu