Wprowadzenie do programowania obiektowego w Pythonie
George Boorman
Curriculum Manager, DataCamp
class Customer:# Code for class goes herepass
class <name>: rozpoczyna definicję klasyclass jest wciętypass, aby utworzyć "pustą" klasęc_one = Customer()
c_two = Customer()
ClassName(), aby utworzyć obiekt klasy ClassNameclass Customer:def identify(self, name): print("I am Customer " + name)
self jako pierwszego argumentu w definicji metodycust = Customer()
cust.identify("Laura")
I am Customer Laura
self podczas wywoływania metody na obiekcieclass Customer:
def identify(self, name):
print("I am Customer " + name)
cust = Customer()
cust.identify("Laura")
self powinien być pierwszym argumentem każdej metodyself jest zastępnikiem (jeszcze nieistniejącego) obiektucust.identify("Laura") zostanie zinterpretowane jako Customer.identify(cust, "Laura")Customer powinno być atrybutem
$$\text{\Large{Atrybuty tworzy się przez przypisanie (=) w metodach}}$$
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
Wprowadzenie do programowania obiektowego w Pythonie