Переопределение функционала базового класса

Переопределение функционала базового класса

@ProgHelpBot
  1. Переопределение функционала базового класса
  2. Проверка типа объекта

Переопределение функционала базового класса

Выражение super() позволяет обращаться к базовому классу и вызывать его методы.

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

  @property
  def name(self):
    return self.__name

  def display_info(self):
    print(f"Name: {self.__name}")


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

  def display_info(self):
    super().display_info()
    print(f"Company: {self.company}")


alex = Employee("Alex", "Google")
alex.display_info()  # Name: Alex Company: Google

Проверка типа объекта

Функция isinstance() проверяет, принадлежит ли объект к данному типу. Если да, возвращает True, иначе False.

isinstance([объект], [тип])

Пример:

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

  @property
  def name(self):
    return self.__name

  def do_nothing(self):
    print(f"{self.__name} does nothing")


class Student(Person):
  def study(self):
    print(f"{self.name} studies")


class Employee(Person):
  def work(self):
    print(f"{self.name} works")


def act(person):
  if isinstance(person, Student):
    person.study()
  elif isinstance(person, Employee):
    person.work()
  elif isinstance(person, Person):
      person.do_nothing()


alex = Person("Alex")
bill = Student("Bill")
Carl = Employee("Carl")

act(alex)  # Alex does nothing
act(alice)  # Bill studies
act(tom)  # Carl works


← Наследование

→ Атрибуты классов и статические методы

Report Page