我正在尝试使用魔术方法__getattr__
和创建一个圆类__setattr__
,我似乎有我的__getattr__
工作,但是当我实现时__setattr__
(如果值是一个int,它应该只允许设置x
和y
的值,并引发一个AttributeError
when用户尝试设置属性area
,circumference
和distance
to circle
), 我的__getattr__
会抛出最大递归错误。当我将其注释掉时,__getattr__
then 工作得很好。
from math import pi, hypot, sqrt
'''
Circle class using __getattr__, and __setattr__ (rename circle2)
'''
# __getattr__(self, name): Automatically called when the attribute name
# is accessed and the object has no such attribute.
# __setattr__(self, name, value): Automatically called when an attempt is made to bind the attribute name to value.
class Circle:
def __init__(self, x, y, r):
self.x = x
self.y = y
self.r = r
self.area = pi * self.r * self.r
self.circumference = 2 * pi * self.r
self.distance_to_origin = abs(sqrt((self.x - 0)*(self.x - 0) + (self.y - 0) * (self.y - 0)) - self.r)
def __getattr__(self, name):
if name in ["x", "y", "r", "area", "circumference", "distance_to_origin"]:
print('__get if statement') # check getattr working
return getattr(self, name)
else:
print('Not an attribute')
return None
'''
def __setattr__(self, name, value):
print(name, value)
if name in ['x', 'y']:
if isinstance(value, int):
print('we can set x,y')
self.__dict__[name] = value
else: # value isn't an int
raise TypeError('Expected an int')
elif name in ['area', 'circumference', 'distance_to_origin']:
raise RuntimeError('Cannot set attribute')
'''
if __name__ == '__main__':
circle = Circle(x=3, y=4, r=5)
# print(circle.x)
print(circle.__getattr__('x'))
# print(circle.y)
print(circle.__getattr__('y'))
# print(circle.r)
print(circle.__getattr__('r'))
# print(circle.area)
print(circle.__getattr__('area'))
# print(circle.circumference)
print(circle.__getattr__('circumference'))
# print(circle.distance_to_origin)
print(circle.__getattr__('distance_to_origin'))
# print(circle.test)
'''
tests = [('circle.x = 12.3', "print('Setting circle.x to non-integer fails')"),
('circle.y = 23.4', "print('Setting circle.y to non-integer fails')"),
('circle.area = 23.4', "print('Setting circle.area fails')"),
('circle.circumference = 23.4', "print('Setting circle.circumference fails')"),
('circle.distance_to_origin = 23.4', "print('Setting circle.distance_to_origin fails')"),
('circle.z = 5.6', "print('Setting circle.z fails')"),
('print(circle.z)', "print('Printing circle.z fails')")]
for test in tests:
try:
exec(test[0])
except:
exec(test[1])
'''
和__setattr__
注释掉后,测试代码
if __name__ == '__main__':
circle = Circle(x=3, y=4, r=5)
# print(circle.x)
print(circle.__getattr__('x'))
# print(circle.y)
print(circle.__getattr__('y'))
# print(circle.r)
print(circle.__getattr__('r'))
# print(circle.area)
print(circle.__getattr__('area'))
# print(circle.circumference)
print(circle.__getattr__('circumference'))
# print(circle.distance_to_origin)
print(circle.__getattr__('distance_to_origin'))
打印出来:
__get if statement
3
__get if statement
4
__get if statement
5
__get if statement
78.53981633974483
__get if statement
31.41592653589793
__get if statement
0.0