x
eta y
x = 5.4
y = 1.8
print(f'Point: ({x},{y})')
p = (5.4,1.8)
print(f'Point: ({p[0]},{p[1]})')
Klasearen definizioa:
class Point(object):
"""A 2-dimensional point"""
help(Point)
Help on class Point in module __main__: class Point(builtins.object) | A 2-dimensional point | | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined)
Point
izeneko klase bat sortzean, Point
klase objektu berezia sortzen da.
Point motako objektuak sortzen...
p = Point()
print(p,type(p))
<__main__.Point object at 0x7fad001c7310> <class '__main__.Point'>
Objektu batetan eremuak sor daitezke.
p = Point()
p.x = 5.4
p.y = 1.8
print(f'Point: ({p.x},{p.y})')
Point: (5.4,1.8)
__init__()
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
p = Point(5.4,1.8)
print(f'Point: ({p.x},{p.y})')
Point: (5.4,1.8)
__init__(self,x,y)
-eko lehenengo argumentua, self
, berezia daPoint
objektuaren erreferentzia da, __init__
funtzioak hasieratuko duena.self
erabiltzen da.Point(5.4,1.8)
funtzioko 2 argumentuak __init__(self,x,y)
-en argumentu bilakatzen dira (2. eta 3.)class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
p = Point(5.4,1.8)
z = list("aeiou")
z.append(123)
p = Point(5.4,1.8)
p.funtzio_izena(argumentuak...)
Puntu baten testu errepresentazioa bueltatzen duen funtzio bat izatea interesgarria litzateke, adibidez:
$$ p = Point(3,8) \;\; \Rightarrow \;\; p.str() \;\equiv\; "(3,8)" $$from math import sqrt
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def str(self):
return f'({self.x},{self.y})'
p = Point(3,8)
print(p.str())
print(Point.str(p))
(3,8) (3,8)
def str(self):
return f'({self.x},{self.y})'
p.str()
Funtzioak self
argumentu berezia du
Funtzioa p
objektuaren bidez exekutatzean, argumentu bat gutxiago
p.str()
$\equiv$ Point.str(p)
p.funtzio_izena(a,b,c,d,e)
$\equiv$ Point.funtzio_izena(p,a,b,c,d,e)
print(p.str(),Point.str(p))
(3,8) (3,8)
Puntu baten modulua ondoko moduan defini dezakegu:
$$ |p| \; = \; \sqrt{(x_p)^2 + (y_p)^2} $$from math import sqrt
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def str(self):
return f'({self.x},{self.y})'
def mod(self):
return sqrt(self.x*self.x + self.y*self.y)
p = Point(5.4,1.8)
print(p.mod() , Point.mod(p))
5.692099788303083 5.692099788303083
Bi punturen batuketa eta kenketa ere defini ditzakegu:
$$ p + q \; \equiv \; (x_p+x_q) \;,\; (y_p+y_q) $$$$ p - q \; \equiv \; (x_p-x_q) \;,\; (y_p-y_q) $$→ Funtzio hauen argumentua beste puntu bat izango da.
→ Funtzio hauek puntu berriak bueltatzen dituzte.
from math import sqrt
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def str(self):
return f'({self.x},{self.y})'
def mod(self):
return sqrt(self.x*self.x + self.y*self.y)
def add(self,other):
return Point(self.x + other.x , self.y + other.y)
def sub(self,other):
return Point(self.x - other.x , self.y - other.y)
p = Point(1,2)
q = Point(3,5)
r = p.add(q)
s = p.sub(q)
print(f'{p.str()} + {q.str()} = {r.str()}')
print(f'{p.str()} - {q.str()} = {s.str()}')
(1,2) + (3,5) = (4,7) (1,2) - (3,5) = (-2,-3)
Baina... orain arte egin dugunarekin
print(p.str())
print(p)
print(str(p))
p + q - p
__init__(...)
str()
→ __str__()
repr()
→ __repr__()
len()
→ __len__()
str()
→ __str__()
¶class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def str(self):
return f'({self.x},{self.y})'
Orain arteko klasea ez zegoen str
funtzioarekin "konektatua".
__str__
funtzio bat definitua badu, str
-k hori exekutatuko du.p = Point(5.4,1.8)
str(p)
__str__
funtzioa definitzen badugu, ordea:
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x},{self.y})'
Hemendik aurrera, str
funtzioa erabili ahal izango dugu
p = Point(5.4,1.8)
#str(p)
print(p,str(p),p.__str__(),Point.__str__(p),sep='\n')
(5.4,1.8) (5.4,1.8) (5.4,1.8) (5.4,1.8)
Gainera, beste funtzio batzuk ere, str
funtzioa erabiliko dute...
print(p)
(5.4,1.8)
Dena den, honekin ez dugu dena ebatzi:
z = [1 , 'kaixo' , p]
print(z)
str(z)
[1, 'kaixo', <__main__.Point object at 0x7fad00103390>]
"[1, 'kaixo', <__main__.Point object at 0x7fad00103390>]"
__str__
funtzioak, repr
funtzioa exekutatzen du elementu bakoitzaren gain.kaixo
-ren inguruanEsandakoaren froga:
z = [1 , 'kaixo' , p]
print(z)
print(str(z))
print(f'[{", ".join(repr(x) for x in z)}]')
print(f'[{", ".join(str(x) for x in z)}]')
repr()
→ __repr__()
¶repr
↔ eval
Point(5.4,1.8)
espresioa erabiltzen badugu...repr
-ek bueltatu beharko lukeenaclass Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x},{self.y})'
def __repr__(self):
return f'Point({self.x},{self.y})'
p = Point(5.4,1.8)
print(str(p))
print(repr(p))
(5.4,1.8) Point(5.4,1.8)
repr
↔ eval
propietatea betetzen da:
q = eval(repr(p))
print(p,q,type(p),type(q))
print(p.x == q.x , p.y == q.y, p == q)
eval(repr(p)) == p
(5.4,1.8) (5.4,1.8) <class '__main__.Point'> <class '__main__.Point'> True True False
False
len()
→ __len__()
¶# Errore bat gertatuko da...
len(p)
Gure Point
klasean
from math import sqrt
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x},{self.y})'
def __repr__(self):
return f'Point({self.x},{self.y})'
def mod(self):
return sqrt(self.x*self.x + self.y*self.y)
def __len__(self):
return self.mod()
p = Point(5.4,1.8)
# __len__ funtzioa sortu badugu ere, errore bat gertatuko da...
print(p,'puntuaren luzera:',len(p))
__len__
funtzioak zenbaki oso bat bueltatu behar du, beraz azken aldaketa hau gaizki dago.
Aurreko atalean, repr
↔ eval
erlazioa ebatzi dugu:
p = Point(5.4,1.8)
q = eval(repr(p))
print(p,repr(p),q)
Baina p
eta q
puntuak berdinak ote dira?
print(p, q, p==q, p is q)
==
eragileak ez daki ezertxo ere gure Point
klaseaz<
<=
>
>=
==
!=
+
-
*
/
//
%
+
-
obj[key]
obj[key] = ...
del obj[key]
in
not in
<
<=
>
>=
==
!=
¶a < b
→ a.__lt__(b)
a <= b
→ a.__le__(b)
a > b
→ a.__gt__(b)
a >= b
→ a.__ge__(b)
a == b
→ a.__eq__(b)
a != b
→ a.__ne__(b)
Funtzio hauek sortu ezean, eragileek (batzuk) erroreak sortuko dituzte:
a = Point(1,2)
b = Point(1,2)
print(f'{a} == {b} : {a==b}')
print(f'{a} == {a} : {a==a}')
print(f'{a} != {b} : {a!=b}')
print(f'{a} != {a} : {a!=a}')
# honek errore bat sortuko du
#print(f'a > b : {a>b}')
a == b
, $ \;\; \nexists \_\_eq\_\_\;$ → a is b
a != b
, $ \;\; \nexists \_\_ne\_\_\;$ → a is not b
Point
klasean, ardatzeko balioak erabil genitzake puntuak konparatzeko...Point
klasean, puntuen modulua erabil genezake puntuak konparatzeko...class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x},{self.y})'
def __repr__(self):
return f'Point({self.x},{self.y})'
def mod(self):
return sqrt(self.x*self.x + self.y*self.y)
def __eq__(self,other):
return self.x == other.x and self.y == other.y
def __ne__(self,other):
return self.x != other.x or self.y != other.y
def __gt__(self,other):
return self.mod() > other.mod()
def __ge__(self,other):
return self.mod() >= other.mod()
def __lt__(self,other):
return self.mod() < other.mod()
def __le__(self,other):
return self.mod() <= other.mod()
Orain, bai:
p = Point(1,2)
q = Point(3,4)
print(f'{p} == {q} : {p==q}')
print(f'{p} != {q} : {p!=q}')
print(f'{p} > {q} : {p>q}')
print(f'{p} >= {q} : {p>=q}')
print(f'{p} < {q} : {p<q}')
print(f'{p} <= {q} : {p<=q}')
(1,2) == (3,4) : False (1,2) != (3,4) : True (1,2) > (3,4) : False (1,2) >= (3,4) : False (1,2) < (3,4) : True (1,2) <= (3,4) : True
+
-
*
/
//
%
¶a + b
→ a.__add__(b)
a - b
→ a.__sub__(b)
a * b
→ a.__mul__(b)
a / b
→ a.__truediv__(b)
a // b
→ a.__floordiv__(b)
a % b
→ a.__mod__(b)
Batuketa eta kenketa defini ditzakegu:
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x},{self.y})'
def __add__(self,other):
return Point(self.x+other.x, self.y+other.y)
def __sub__(self,other):
return Point(self.x-other.x, self.y-other.y)
p = Point(1,2)
q = Point(3,5)
print(f'{p} + {q} = {p+q}')
print(f'{p} - {q} = {p-q}')
(1,2) + (3,5) = (4,7) (1,2) - (3,5) = (-2,-3)
+
-
¶+ a
→ a.__pos__()
- a
→ a.__neg__()
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x}, {self.y})'
def __pos__(self):
#return Point(self.x, self.y)
return self
def __neg__(self):
return Point(-self.x, -self.y)
p = Point(1,2)
print(f'+{p} = {+p}')
print(f'-{p} = {-p}')
+(1, 2) = (1, 2) -(1, 2) = (-1, -2)
obj[key]
¶a[key]
→ a.__getitem__(key)
Zentzurik ez badu ere puntu bat indexatzea, funtzioa sortu dezakegu a[key]
patroia konprobatzeko:
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x},{self.y})'
def __getitem__(self,key):
if key == 'x' :
return self.x
elif key == 'y' :
return self.y
else :
return None
#raise ...
p = Point(1,2)
print(f'p["x"] = {p["x"]}')
print(f'p["y"] = {p["y"]}')
print(f'p["kk"] = {p["kk"]}')
print(f'p[1] = {p[1]}')
p["x"] = 1 p["y"] = 2 p["kk"] = None p[1] = None
obj[key] = ...
¶a[key] = value
→ a.__setitem__(key,value)
Berriro ere, ez du zentzu handirik, baina frogatzearren...
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x},{self.y})'
def __setitem__(self,key,value):
if key == 'x' :
self.x = value
elif key == 'y' :
self.y = value
else :
# raise ....
print(f'??? Puntuko {repr(key)} gakoari {repr(value)} balioa esleitu nahi diozu?')
p = Point(1,2)
print(p)
p["x"] = 100
print(p)
p["y"] = 200
print(p)
p[0] = "kk"
(1,2) (100,2) (100,200) ??? Puntuko 0 gakoari 'kk' balioa esleitu nahi diozu?
del obj[key]
¶del a[key]
→ a.__delitem__(key)
Berriro ere, ez du zentzu handirik, baina frogatzearren...
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x},{self.y})'
def __delitem__(self,key):
print(f'??? Puntuko {repr(key)} gakoari dagokion elementua ezabatu nahi duzu?')
p = Point(1,2)
del p["x"]
del p[0]
??? Puntuko 'x' gakoari dagokion elementua ezabatu nahi duzu? ??? Puntuko 0 gakoari dagokion elementua ezabatu nahi duzu?
in
not in
¶value in a
→ a.__contains__(value)
value not in a
→ not a.__contains__(value)
Berriro ere, ez du zentzu handirik, baina frogatzearren...
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x},{self.y})'
def __contains__(self,key):
return True if key == 'x' or key == 'y' else False
p = Point(1,2)
print('x' in p, 'y' in p, 'kk' in p , 1 in p)
True True False False
class Point(object):
"""A 2-dimensional point"""
def __init__(self,x=0,y=0):
self.x = x
self.y = y
def mod(self):
return sqrt(self.x*self.x + self.y*self.y)
def __str__(self):
return f'({self.x},{self.y})'
def __repr__(self):
return f'Point({self.x},{self.y})'
def __eq__(self,other):
return self.x == other.x and self.y == other.y
def __ne__(self,other):
return self.x != other.x or self.y != other.y
def __gt__(self,other):
return self.mod() > other.mod()
def __ge__(self,other):
return self.mod() >= other.mod()
def __lt__(self,other):
return self.mod() < other.mod()
def __le__(self,other):
return self.mod() <= other.mod()
def __add__(self,other):
return Point(self.x+other.x,self.y+other.y)
def __sub__(self,other):
return Point(self.x-other.x,self.y-other.y)
def __pos__(self):
return self
def __neg__(self):
return Point(-self.x,-self.y)
GOGORATU: Python-ek funtzio berezien erabilera handia egiten du
https://docs.python.org/3/reference/datamodel.html#special-method-names