Introduction to Object-Oriented Programming in Python
George Boorman
Curriculum Manager, DataCamp
class Customer:
# Code for class goes here
pass
class <name>:
starts a class definition class
is indentedpass
to create an "empty" classc_one = Customer()
c_two = Customer()
ClassName()
to create an object of class ClassName
class Customer:
def identify(self, name): print("I am Customer " + name)
self
as the first argument in method definitioncust = Customer()
cust.identify("Laura")
I am Customer Laura
self
when calling a method on an objectclass Customer:
def identify(self, name):
print("I am Customer " + name)
cust = Customer()
cust.identify("Laura")
self
should be the first argument of any methodself
is a stand-in for a (not yet created) objectcust.identify("Laura")
will be interpreted as Customer.identify(cust, "Laura")
Customer
's' name should be an attribute
$$\text{\Large{Attributes are created by assignment (=) in methods}}$$
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
Introduction to Object-Oriented Programming in Python