Object-Oriented Programming in Python
Alex Yarosh
Content Quality Analyst @ DataCamp
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
emp1 = Employee("Teo Mille", 50000)
emp2 = Employee("Marta Popov", 65000)
name
, salary
are instance attributesself
binds to an instanceclass
class MyClass:
# Define a class attribute
CLASS_ATTR_NAME = attr_value
class Employee: # Define a class attribute MIN_SALARY = 30000 #<--- no self.
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 instancesself
to define class attributeClassName.ATTR_NAME
to access the class attribute valueclass 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("TBD", 40000)
print(emp1.MIN_SALARY)
30000
emp2 = Employee("TBD", 60000)
print(emp2.MIN_SALARY)
30000
pi
for a Circle
classclass MyClass: @classmethod # <---use decorator to declare a class method
def my_awesome_method(cls, args...): # <---cls argument refers to the class # Do stuff here # Can't use any instance attributes :(
MyClass.my_awesome_method(args...)
class Employee:
MIN_SALARY = 30000
def __init__(self, name, salary=30000):
self.name = name
if salary >= Employee.MIN_SALARY:
self.salary = salary
else:
self.salary = Employee.MIN_SALARY
__init__()
@classmethod
def from_file(cls, filename):
with open(filename, "r") as f:
name = f.readline()
return cls(name)
return
to return an objectcls(...)
will call __init__(...)
class Employee:
MIN_SALARY = 30000
def __init__(self, name, salary=30000):
self.name = name
if salary >= Employee.MIN_SALARY:
self.salary = salary
else:
self.salary = Employee.MIN_SALARY
@classmethod
def from_file(cls, filename):
with open(filename, "r") as f:
name = f.readline()
return cls(name)
# Create an employee without calling Employee()
emp = Employee.from_file("employee_data.txt")
type(emp)
__main__.Employee
Object-Oriented Programming in Python