Nhập môn Lập trình Hướng đối tượng với Python
George Boorman
Curriculum Manager, DataCamp
class Customer:# Code for class goes herepass
class <name>: bắt đầu định nghĩa lớp class được thụt lềpass để tạo một lớp "trống"c_one = Customer()
c_two = Customer()
ClassName() để tạo một đối tượng của lớp ClassNameclass Customer:def identify(self, name): print("I am Customer " + name)
self làm đối số đầu tiên trong định nghĩa phương thứccust = Customer()
cust.identify("Laura")
I am Customer Laura
self khi gọi một phương thức trên một đối tượngclass Customer:
def identify(self, name):
print("I am Customer " + name)
cust = Customer()
cust.identify("Laura")
self phải là đối số đầu tiên của bất kỳ phương thức nàoself là đại diện cho một đối tượng (chưa được tạo)cust.identify("Laura") sẽ được hiểu là Customer.identify(cust, "Laura")Customer's' name nên là một thuộc tính$$\text{\Large{Các thuộc tính được tạo bằng phép gán (=) trong các phương thức}}$$
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
Nhập môn Lập trình Hướng đối tượng với Python