Class vs. instance attributes

Introduction to Object-Oriented Programming in Python

George Boorman

Curriculum Manager, DataCamp

Core principles of OOP

Encapsulation:

  • Bundling of data and methods

Inheritance:

  • Extending the functionality of existing code

Polymorphism:

  • Creating a unified interface
Introduction to Object-Oriented Programming in Python

Instance-level attributes

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

emp1 = Employee("Teo Mille", 50000) 
emp2 = Employee("Marta Popov", 65000)
  • name and salary values are specific to each object
  • self assigns to an object
Introduction to Object-Oriented Programming in Python

Class-level attributes

  • Data shared among all instances of a class

 

  • Define class attributes in the body of class

 

  • "Global variable" within the class
Introduction to Object-Oriented Programming in Python

Implementing class-level attributes

class Employee:
    # Define a class attribute
    # No self. syntax
    MIN_SALARY = 30000 

def __init__(self, name, salary): self.name = name # Use class name # to access class attribute if salary >= Employee.MIN_SALARY: self.salary = salary
else: self.salary = Employee.MIN_SALARY
  • MIN_SALARY is shared among all instances
  • Don't use self to define class attribute
  • Convention is to use capital letters
  • Use ClassName.ATTR_NAME to access the class attribute value
Introduction to Object-Oriented Programming in Python

Class-level attributes

class Employee:
    # Define a class attribute
    MIN_SALARY = 30000    

def __init__(self, name, salary): self.name = name # Use class name # to access class attribute if salary >= Employee.MIN_SALARY: self.salary = salary else: self.salary = Employee.MIN_SALARY
emp1 = Employee("John", 40000)
print(emp1.MIN_SALARY)
30000
emp2 = Employee("Jane", 60000)
print(emp2.MIN_SALARY)
30000
Introduction to Object-Oriented Programming in Python

Modifying class-level attributes

emp1 = Employee("John", 40000)
emp2 = Employee("Jane", 60000)

# Update MIN_SALARY of emp1 emp1.MIN_SALARY = 50000
# Print MIN_SALARY for both employees print(emp1.MIN_SALARY) print(emp2.MIN_SALARY)
50000
30000
Introduction to Object-Oriented Programming in Python

Modifying class-level attributes

  • MIN_SALARY is created in the class definition

 

  • Updating MIN_SALARY of an object will not affect the value in the class definition

 

  • Security - prevent changes being made to software!
Introduction to Object-Oriented Programming in Python

Why use class attributes?

 

  • Minimum and maximum values for attributes
    • Prevent invalid data
  • Commonly used values and constants, e.g. host, port for a Database class
    • Avoid repetition when creating objects
Introduction to Object-Oriented Programming in Python

Let's practice!

Introduction to Object-Oriented Programming in Python

Preparing Video For Download...