Class methods

Introduction to Object-Oriented Programming in Python

George Boorman

Curriculum Manager, DataCamp

Methods

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def give_raise(self, amount):
        self.salary += amount


# Unique attribute values emp_one = Employee("John", 40000)
emp_one.give_raise(5000) print(emp_one.salary)
45000









# Unique attribute values emp_two = Employee("Jane", 60000)
emp_two.give_raise(5000) print(emp_two.salary)
65000
Introduction to Object-Oriented Programming in Python

Class methods

  • Possible to define class methods
  • Must have a narrow scope because they can't use object-level data
class MyClass:
    # Use a decorator to declare a class method
    @classmethod

# cls argument refers to the class def my_awesome_method(cls, args...): # Do stuff here # Can't use any instance attributes
# Call the class, not the object MyClass.my_awesome_method(args...)
  • As with self, cls is a convention but any word will work
Introduction to Object-Oriented Programming in Python

Alternative constructors

class Employee:
  def __init__(self, name, salary):
      self.name = name
      self.salary = salary

@classmethod def from_file(cls, filename): with open(filename, "r") as f: # Read the first line name = f.readline().strip() # Read the second line as integer salary = int(f.readline().strip())
return cls(name, salary)
  • Allow alternative constructors
  • Can only have one __init__()

 

  • Use class methods to create objects
  • Use return to return an object
  • cls(...) will call __init__(...)
Introduction to Object-Oriented Programming in Python

Alternative constructors

class Employee:
  def __init__(self, name, salary):
      self.name = name
      self.salary = salary
  @classmethod
  def from_file(cls, filename):
      with open(filename, "r") as f:
          name = f.readline().strip()
          salary = int(f.readline().strip())
      return cls(name, salary)  

Employee.txt

Text file containing the name John Smith and salary 40000

# Create an employee without calling Employee()
emp = Employee.from_file("employee_data.txt")
print(emp.name)
John Smith
Introduction to Object-Oriented Programming in Python

When to use class methods

  • Alternative constructors

  • Methods that don't require instance-level attributes

  • Restricting to a single instance (object) of a class

    • Database connections
    • Configuration settings
Introduction to Object-Oriented Programming in Python

Let's practice!

Introduction to Object-Oriented Programming in Python

Preparing Video For Download...