Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
python, attributes, setter and getter the pythonic way (V2)
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 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) 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
run
|
edit
|
history
|
help
0
PyWeekD
gj
inerse_matrix_gauss_jordan
pytest
ct
python_study_note_for loop@nested loop
Traceback with newline
Prueba
shivareddy error
PyDeque