Einführung in objektorientierte Programmierung 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 und salary sind für jedes Objekt spezifischself weist dem Objekt zu
class-Rumpf definieren
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 wird von allen Instanzen geteiltself nicht zum Definieren von Klassenattributen verwendenClassName.ATTR_NAME auf den Klassenattributwert zugreifenclass 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 wird in der Klassendefinition erstellt
MIN_SALARY an einem Objekt ändert den Klassenwert nicht
host, port für eine Database-KlasseEinführung in objektorientierte Programmierung in Python