Introduction to Object-Oriented Programming in Python
George Boorman
Curriculum Manager, DataCamp
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
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...)
self
, cls
is a convention but any word will workclass 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)
__init__()
return
to return an objectcls(...)
will call __init__(...)
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)
# Create an employee without calling Employee()
emp = Employee.from_file("employee_data.txt")
print(emp.name)
John Smith
Alternative constructors
Methods that don't require instance-level attributes
Restricting to a single instance (object) of a class
Introduction to Object-Oriented Programming in Python