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
emp1 = Employee("Teo Mille", 50000)
emp2 = Employee("Marta Popov", 65000)
name
and salary
values are specific to each objectself
assigns to an object
class
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 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("John", 40000)
print(emp1.MIN_SALARY)
30000
emp2 = Employee("Jane", 60000)
print(emp2.MIN_SALARY)
30000
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
MIN_SALARY
is created in the class definition
MIN_SALARY
of an object will not affect the value in the class definition
host
, port
for a Database
classIntroduction to Object-Oriented Programming in Python