Hack Bulgaria
github.com/HackBulgaria
>>> type(42)
<class 'int'>
>>> type([])
<class 'list'>
>>> type([]) is list
True
>>> type(list)
<class 'type'>
>>> type(list) is type
True
>>> type(type)
<class 'type'>
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
spam = Vector(1.0, 1.0)
class Panda:
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def get_buffed(self):
if self.weight < 1000:
self.weight += 1
def eat_bamboo(self):
self.get_buffed()
return "Nomm nomm nomm!"
def celebrate_birthday(self):
self.age += 1
Classes in python are "open"
attributes/methods starting with _ are "protected"
attributes/methods starting with __ are "private". This is also called Name mangling and the Python interpreter does it itself.
class Panda:
def __init__(self, name, age, weight):
self.name = name
self._age = age
self.__weight = weight
def _get_buffed(self):
if self.__weight < 1000:
self.__weight += 1
def eat_bamboo(self):
self._get_buffed()
return "Nomm nomm nomm!"
def celebrate_birthday(self):
self._age += 1
import math
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def length(self):
return math.sqrt(self.x^2 + self.y^2)
v1 = Vector(2.0, 3.0)
v2 = Vector(1.0, 2.0)
print(Vector.length(v1))
print(Vector.length(v2))
Known also as "magic methods",
"dunder"(double under) methods in Python override some aspects of the behavior of our objects.
class Panda:
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def _get_buff(self):
if self.weight < 1000:
self.weight += 1
def eat_bamboo(self):
self._get_buff()
return "Nomm nomm nomm!"
def __str__(self):
return "I am a panda - {}".format(self.name)
v = Vector(4.0, 5.0)
print(getattr(v, 'y')) # 5.0
setattr(v, 'y', 10.0)
print(getattr(v, 'y')) # 10.0
By Hack Bulgaria