Class anatomy: attributes and methods

Introduction to Object-Oriented Programming in Python

George Boorman

Curriculum Manager, DataCamp

A Customer class

class Customer:

# Code for class goes here
pass
  • class <name>: starts a class definition
  • Code inside class is indented
  • Use pass to create an "empty" class
c_one = Customer()
c_two = Customer()
  • Use ClassName() to create an object of class ClassName
Introduction to Object-Oriented Programming in Python

Add methods to a class

class Customer:  

def identify(self, name): print("I am Customer " + name)
  • Method definition = function definition within class
  • Use self as the first argument in method definition
cust = Customer()
cust.identify("Laura")
I am Customer Laura
  • Ignore self when calling a method on an object
Introduction to Object-Oriented Programming in Python
class Customer:  
    def identify(self, name):
        print("I am Customer " + name)

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

What is self?

  • Classes are templates
  • self should be the first argument of any method
  • self is a stand-in for a (not yet created) object
  • cust.identify("Laura") will be interpreted as Customer.identify(cust, "Laura")
Introduction to Object-Oriented Programming in Python

We need attributes

  • OOP bundles data with methods that operate on data
    • Customer's' name should be an attribute

 

$$\text{\Large{Attributes are created by assignment (=) in methods}}$$

Introduction to Object-Oriented Programming in Python

Add an attribute to class

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

Old version

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 

New version

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

Let's practice!

Introduction to Object-Oriented Programming in Python

Preparing Video For Download...