Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
python, Polymorphie, attributes, setter and getter the pythonic way (V3)
from abc import abstractmethod class P: def __init__(self, x=0): self.__x = x def set_x(self, x): self.__x = x def get_x(self): return self.__x class P1: def __init__(self, x=0): self.x = x # calls the setter method not direct writing def __set_x(self, x): self.__x = x if x > 0 else -x def __get_x(self): return self.__x x = property(__get_x, __set_x) class P2: def __init__(self, x=0): self.x = x # self.x reference the setter method and not the attr @property def x(self): return self.__x @x.setter def x(self, x): if x < 0: raise ValueError('negativ number not allowed ..warum auch immer...') self.__x = x class P3: def __init__(self, x=0, y=0): #self.__x = x # we call the setter instead self.x = x #self.__y = y # we call the setter instead... self.y = y @property def x(self): return self.__x @x.setter def x(self, x): self.__x = x if x > 0 else -x @property def y(self): return self.__y @y.setter def y(self, y): self.__y = y if y > 0 else -y p30 = P3(12,14) print(p30.x, p30.y) p30.x = 120 p30.y = 140 print(p30.x, p30.y) p30.x = -120 p30.y = -140 print(p30.x, p30.y) p11 = P1(-15) print('p11.x', p11.x) p11.x = -17 print('p11.x', p11.x) #p11.__set_x(-19) # not im scope like private... #print('p11.x', p11.__get_x()) # also here... p1 = P() p2 = P(12) print("p1.get_x(): {}, p2.get_x(): {}".format(p1.get_x(), p2.get_x())) p21 = P2() p22 = P2(12) print("p21.x: {}, p22.x: {}".format(p21.x, p22.x)) try: p33 = P2(-14) except ValueError as err: print('Error has occured:', err) else: print(p33.x) finally: pass class A: @abstractmethod def m(self): pass class B(A): def m(self): print('method m, class B') class C(A): def m(self): print('method m, class C') class D(A): def m(self): print('method m, class D') class E: def m(self): print('method m, class E') obj_b = B() obj_c = C() obj_d = D() obj_e = E() def m(*obj_as): for a in obj_as: if isinstance(a, A): a.m() m(obj_b, obj_c, obj_d, obj_e)
run
|
edit
|
history
|
help
0
sept
Creating Person class
substring
Привет
snake water gun game
total_tips
aaa
f strings 2
Add missing names
abstractmethod