Podstawy programowania obiektowego

Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Jake Roach

Data Engineer

Definiowanie klasy

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
    self.height = 0

# This invokes a call to __init__
john = Person("John Casey", 38)
  • Klasę definiuje się za pomocą słowa kluczowego class
  • __init__ jest konstruktorem – wywoływanym przy tworzeniu nowego obiektu klasy
  • self odnosi się do bieżącej instancji klasy
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Atrybuty instancji

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
# Create an instance of Person
sarah = Person("Sarah Walker", 31)
sarah.age  # Retrieve the age instance attribute
  • Powiązane z obiektem klasy
  • Można je ustawiać i pobierać za pomocą składni self.<attribute-name>
  • Dostęp przez <object-name>.<attribute-name>
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Atrybuty klasy

  • Powiązane z samą klasą
  • Można je pobierać bez obiektu klasy
  • Przechowują dane wspólne dla wszystkich obiektów klasy
class Person:
  residence = "Planet Earth"
  ...
# Accessed without an instance
print(Person.residence)
Planet Earth
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Metody instancji

class Person:
  ...
  def introduce(self):
      print(f"Hello, my name is {self.name}")
chuck = Person("Chuck", 32)
chuck.introduce()  # Called on a Person object

$$

  • Wymagają istnienia obiektu klasy do wywołania
  • Przyjmują słowo kluczowe self jako pierwszy parametr
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Metody klasy

class Person:
  @classmethod
  def wake_up(cls):
      print("Time to start your day!")
# Calling a class method
Person.wake_up()

$$

  • Dekorowane za pomocą @classmethod
  • Nie wymagają obiektu klasy do wywołania
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Dziedziczenie

Dziedziczenie umożliwia ponowne użycie kodu między klasami

  • Klasa potomna (Employee) dziedziczy całą funkcjonalność klasy nadrzędnej (Person)
  • Relacja „jest"
  • Może implementować dodatkową funkcjonalność
    • Atrybuty
    • Metody
class Person:
  def __init__(self, name, age):
    self.name
    self.age = age

  def introduce(self):
      print(f"Hello, my name is {self.name}")
class Employee(Person):
  def __init__(self, name, age, title):
    Person.__init__(self, name, age)
    self.title = title

  def change_position(self, new_title):
      self.title = new_title
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Dziedziczenie

lester = Employee("Lester", 26, "Technician")
lester.introduce()  # Inherited from Person
print(lester.title)
Hello, my name is Lester
Technician
lester.change_position("Cashier")
print(lester.title)
Cashier
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

super()

class Employee(Person):
  def __init__(self, name, age, title):
    # Uses name of the parent class
    Person.__init__(self, name, age)

    self.title = title
  ...
  • Nazwa klasy, __init__()

Użycie super()

class Employee(Person):
  def __init__(self, name, age, title):
    # super(), instead of class name
    super().__init__(name, age)

    self.title = title
  ...
  • super(), __init__()
  • Nie trzeba przekazywać self
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Przesłanianie

Klasa potomna implementuje odziedziczoną metodę w nowy sposób

class Employee(Person):
  ...
  def introduce(self):
      print(f"""My name is {self.name},
        I am a {self.title}""")
lester = Employee("Lester", 26, "Technician")
lester.introduce()
My name is Lester, I am a Technician
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Przeciążanie

class Person:
  def __init__(self, name):
      self.name = name

  def __eq__(self, other):
      return self.name == other.name

$$

  • Dostosowuje zachowanie operatorów Pythona dla klasy
  • __eq__() służy do przeciążenia operatora ==

$$

$$

$$

$$

# Compare two Person objects
chuck = Person("Charles Carmichael")
charles = Person("Charles Carmichael")
print(chuck == charles)
True
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Czas na ćwiczenia!

Programowanie obiektowe w Pythonie – poziom średnio zaawansowany

Preparing Video For Download...