Python for 101s

Какво ще правим?

Днес ще си говорим за ООП!

class Panda:

    def __init__(self, name):
        self.name = name
        self.weight = 100

    def eat(self):
        print("Num num numb")
        self.weight += 1

pandarian = Panda("Pandarian")
pandarian.eat()

Private/protected

  1. Методи и атрибути започващи с _ са protected, би следвало да се ползват само от методи на класа и наследяващи го класове
  2. Методи и атрибути започващи с __ са private, би следвало да се ползват само от методи на класа

__private / _protected

class Panda:

    def __init__(self, name):
        self.name = name
        self._color = "black and white"

    def paint(self, color):
        self._color = color

pandarian = Panda("Pandarian")
pandarian.paint('red')
print(pandarian._color)

mutable vs. immutable

class Fraction:

    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Fraction.gcd(b, a % b)

    def __init__(self, numerator, denumerator):
        self.numerator = numerator
        self.denumerator = denumerator

    def simplify(self):
        gcd = Fraction.gcd(self.numerator, self.denumerator)
        self.numerator /= gcd
        self.denumerator /= gcd

    def simplified(self):
        gcd = Fraction.gcd(self.numerator, self.denumerator)
        numerator = self.numerator / gcd
        denumerator = self.numerator / gcd

        return Fraction(numerator, denumerator)

== / is

  • Проверяваме дали две имена сочат към един и същ обект с is
  • Сравняваме стойностите на два обекта с ==
  • == вика __eq__
  • __eq__ по подразбиране вика is
class Fraction:

    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Fraction.gcd(b, a % b)

    def __init__(self, numerator, denumerator):
        self.numerator = numerator
        self.denumerator = denumerator

    def simplify(self):
        gcd = Fraction.gcd(self.numerator, self.denumerator)
        self.numerator /= gcd
        self.denumerator /= gcd

    def simplified(self):
        gcd = Fraction.gcd(self.numerator, self.denumerator)
        numerator = self.numerator / gcd
        denumerator = self.numerator / gcd

        return Fraction(numerator, denumerator)

    def __eq__(self, other):
        me = self.simplified()
        other = other.simplified()
        return me.numerator == other.numerator 
            and me.denumerator == other.denumerator

__dunder__

  • __add__(self, other) - self + other
  • __sub__(self, other) - self - other
  • __mul__(self, other) - self * other
  • __truediv__(self, other) - self / other
  • __floordiv__(self, other) - self // other
  • __mod__(self, other) - self % other
  • __lshift__(self, other) - self << other
  • __rshift__(self, other) - self >> other
  • __and__(self, other) - self & other
  • __xor__(self, other) - self ^ other
  • __or__(self, other) - self | other
  • __int__(self) - int(обект)
  • __float__(self) - float(обект)
  • __complex__(self) - complex(обект)
  • __bool__(self) - bool(обект)
  • __call__(self) - self()
  • __del__(self) - destructor

Динамично извикване на атрибути getattr/setattr

 

attr = input("what to get?")
getattr(pandarian, attr)
setattr(pandarian, 'color', 'green')

Какво ли викат getattr и setattr?

1. В Python има наследяване

2. Всичко наследява от object

3. Имаме и множествено наследяване!

Mixins

class Blasters: pass
class Bazuka: pass
class ReactionEngine: pass
class Wheel: pass
class GPS: pass

class SpaceShip(Blasters, Bazuka, ReactionEngine, Wheel, GPS):
    pass

Грешки

try:
    # блок
except Изключение/tuple от Изключения:
    # блок за хващане

except ДругоИзключение:
    # блок за хващане и обработка на някое от описаните изключения
except:
    # блок за хващане и обработка на което и да е изключение
else:
    # блок изпълняващ се, ако не е възникнала изключителна ситуация
finally:
    # блок изпълняващ се винаги

Exception hierarchy

Custom Exceptions

 

class BottleEmptyError(Exception):
    def __init__(self):
        self.message = 'No whater in the bottle'

Python Week - Day 3

By Hack Bulgaria

Python Week - Day 3

  • 1,697