4
import math
class Circulo():
def __init__(self):
super()
self.__raio = None
def get_perimetro(self):
return 2 * math.pi * self.raio
def get_area(self):
return math.pi * self.raio ** 2
@property
def raio(self):
return self.__raio
@raio.setter
def raio(self, x):
self.__raio = x
I have the above class and wish to encapsulate the access so that dynamic attributes in the instance are not possible.
ex:
c = Circulo()
c.raio = 2 # ok
c.lado = 2 # AttributeError
I tried to block dynamic attributes with getattr
and setattr
, but I was unsuccessful.
def __getattr__(self, item):
if item in self.__dict__:
return self.__dict__[item]
else:
raise AttributeError('Paramentro ou atributo "%s" inexistente.' % item)
def __setattr__(self, key, value):
if key in self.__dict__:
self.__dict__[key] = value
else:
raise AttributeError('Paramentro ou atributo "%s" inexistente.' % key)
Response-related: What is the purpose of
__slots__
?– Woss
Thanks @Anderson Carlos Woss, thank you so much!!! I’m going to study this one slots now!! ;D
– britodfbr
Anderson Carlos Woss, + a doubt. @Property becomes unnecessary?
– britodfbr
That’s for you to say. As yours get/set only return and assign value without any business rule, yes, it is unnecessary. You can only use the attribute as "public".
– Woss
Thanks Anderson. Thank you very much. I expanded my knowledge with your help.
– britodfbr