Hack Bulgaria
github.com/HackBulgaria
Днес ще си говорим за ООП!
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()
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)
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)
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__
attr = input("what to get?")
getattr(pandarian, attr)
setattr(pandarian, 'color', 'green')
Какво ли викат getattr и setattr?
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:
# блок изпълняващ се винаги
class BottleEmptyError(Exception):
def __init__(self):
self.message = 'No whater in the bottle'
By Hack Bulgaria