Class anatomy: attributes and methods

Object-Oriented Programming in Python

Alex Yarosh

Content Quality Analyst @ DataCamp

A basic 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
c1 = Customer()
c2 = Customer()
  • use ClassName() to create an object of class ClassName
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 1st argument in method definition
cust = Customer()
cust.identify("Laura")
I am Customer Laura
  • ignore self when calling method on an object
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, how to refer data of a particular object?
  • self is a stand-in for a particular object used in class definition
  • should be the first argument of any method
  • Python will take care of self when method called from an object:

cust.identify("Laura") will be interpreted as Customer.identify(cust, "Laura")

Object-Oriented Programming in Python

We need attributes

  • Encapsulation: bundling data with methods that operate on data
  • E.g. Customer's' name should be an attribute

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

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 self.name = new_name # <-- will create .name when set_name is called
cust = Customer()                   # <--.name doesn't exist here yet

cust.set_name("Lara de Silva") # <--.name is created and set to "Lara de Silva"
print(cust.name) # <--.name can be used
Lara de Silva
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
Object-Oriented Programming in Python

Let's practice!

Object-Oriented Programming in Python

Preparing Video For Download...