Introduktion till objektorienterad programmering i 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 och salary är specifika för varje objektself tilldelar till ett objekt
class-kroppen
class Employee: # Define a class attribute # No self. syntax MIN_SALARY = 30000def __init__(self, name, salary): self.name = name # Use class name # to access class attribute if salary >= Employee.MIN_SALARY: self.salary = salaryelse: self.salary = Employee.MIN_SALARY
MIN_SALARY delas av alla instanserself för att definiera ett klassattributClassName.ATTR_NAME för att komma åt klassattributets värdeclass Employee: # Define a class attribute MIN_SALARY = 30000def __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 definieras i klassdefinitionen
MIN_SALARY på ett objekt påverkar inte värdet i klassdefinitionen
host, port för en Database-klassIntroduktion till objektorienterad programmering i Python