我正在尝试使用魔术方法__getattr__
和__setattr__
创建一个圆圈类,我似乎让__getattr__
工作,但是当我实施__setattr__
时(如果值为int,则应仅允许设置x
和y
的值,并在用户尝试设置属性AttributeError
时引发area
,circumference
和distance
到circle
),我的__getattr__
会抛出最大递归错误。当我发表评论时,__getattr__
然后工作得很好。
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
答案 0 :(得分:1)
根据此处的讨论,这是一个较短且改进的版本。实现与原始解决方案相同:
from math import pi, hypot, sqrt
class Circle:
def __init__(self, x, y, r):
self.x = x
self.y = y
super().__setattr__('r', r)
super().__setattr__('area', pi * self.r * self.r)
super().__setattr__('circumference', 2 * pi * self.r)
super().__setattr__('distance_to_origin',
abs(sqrt(self.x * self.x + self.y * self.y) - self.r))
def __setattr__(self, name, value):
if name in ['x', 'y']:
if isinstance(value, int):
print('we can set x,y')
super().__setattr__(name, value)
else: # value isn't an int
raise TypeError('Expected an int for: {}'.format(name))
else:
raise AttributeError('Cannot set attribute: {}'.format(name))
一起避免__getattr__()
所有并使用标记self._intialized
来表示__init__()
是否已经运行会发挥作用:
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._intialized = False
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 * self.x + self.y * self.y) - self.r)
self._intialized = True
def __setattr__(self, name, value):
if name in ['_intialized']:
self.__dict__[name] = value
return
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 for: {}'.format(name))
elif not self._intialized:
self.__dict__[name] = value
elif name in ['area', 'circumference', 'distance_to_origin']:
raise AttributeError('Cannot set attribute: {}'.format(name))
if __name__ == '__main__':
circle = Circle(x=3, y=4, r=5)
print('x:', circle.x)
print('y:', circle.y)
print('r:', circle.r)
print('area:', circle.area)
print('circumference:', circle.circumference)
print('distance_to_origin:', circle.distance_to_origin)
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])
输出看起来不错:
python get_set_attr.py
we can set x,y
we can set x,y
x: 3
y: 4
r: 5
area: 78.53981633974483
circumference: 31.41592653589793
distance_to_origin: 0.0
Setting circle.x to non-integer fails
Setting circle.y to non-integer fails
Setting circle.area fails
Setting circle.circumference fails
Setting circle.distance_to_origin fails
Printing circle.z fails
这将允许使用任何其他名称设置属性:
circle.xyz = 100
但它不会存在:
circle.xyz
Traceback (most recent call last):
File "get_set_attr.py", line 62, in <module>
circle.xyz
AttributeError: 'Circle' object has no attribute 'xyz'
__setattr__
的这种实现可以避免这种情况:
def __setattr__(self, name, value):
if name in ['_intialized']:
self.__dict__[name] = value
return
if name in ['x', 'y']:
if isinstance(value, int):
print('we can set x,y')
self.__dict__[name] = value
return
else: # value isn't an int
raise TypeError('Expected an int for: {}'.format(name))
elif not self._intialized:
self.__dict__[name] = value
else:
raise AttributeError('Cannot set attribute: {}'.format(name))
__getattr__()
?当您访问不存在的属性时,Python会引发AttributeError
:
class A:
pass
a = A()
a.xyz
....
AttributeError: 'A' object has no attribute 'xyz'
仅当属性不存在时,Python才会调用__getattr__()
。
一个用例是另一个对象的包装,而不是使用继承。
例如,我们可以定义使用列表但仅允许列入白名单的属性的ListWrapper
:
class ListWrapper:
_allowed_attrs = set(['append', 'extend'])
def __init__(self, value=None):
self._wrapped = list(value) if value is not None else []
def __getattr__(self, name):
if name in self._allowed_attrs:
return getattr(self._wrapped, name)
else:
raise AttributeError('No attribute {}.'.format(name))
def __repr__(self):
return repr(self._wrapped)
我们可以像列表一样使用它:
>>> my_list = ListWrapper('abc')
>>> my_list
['a', 'b', 'c']
追加元素:
>>> my_list.append('x')
>>> my_list
['a', 'b', 'c', 'x']
但我们不能使用除_allowed_attrs
中定义的属性之外的任何其他属性:
my_list.index('a')
...
AttributeError: No attribute index.
docs说的是什么:
object.__getattr__(self, name)
当属性查找未在通常位置找到属性时调用(即,它不是实例属性,也不是在类树中找到自己)。 name是属性名称。此方法应返回(计算的)属性值或引发
AttributeError
异常。请注意,如果通过常规机制找到该属性,则不会调用
__getattr__()
。 (这是__getattr__()
和__setattr__()
之间的故意不对称。)这是出于效率原因而做的,因为否则__getattr__()
将无法访问实例的其他属性。请注意,至少对于实例变量,您可以通过不在实例属性字典中插入任何值来伪造总控制(而是将它们插入另一个对象中)。请参阅下面的__getattribute__()
方法,了解实际获得对属性访问的完全控制权的方法。
答案 1 :(得分:1)
您可能会对代码中导致问题的几个问题感兴趣。
您无法直接在__init__()
中设置以下内容,因为分配会触发对__setattr__()
的调用,x
仅设置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)
。因此,这些属性从未设置过。
r
您未在__setattr__()
中查看r
。这导致r
以静默方式被忽略,然后当访问area
以在__init__()
中设置__getattr__()
时,名为getattr()
的{{1}}被称为__getattr__()
1}}调用getattr()
等等(因为未设置r
),这导致了递归。
elif name in ['area', 'circumference', 'distance_to_origin']:
raise RuntimeError('Cannot set attribute')
这是固定代码。更改已在下面标记为mod
的评论。
#!/usr/bin/python3
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
# mod : can't set via self.__getattr__
super().__setattr__("r", r)
super().__setattr__("area", pi * self.r * self.r)
super().__setattr__("circumference", 2 * pi * self.r)
super().__setattr__("distance_to_origin", abs(sqrt((self.x - 0)*(self.x - 0) + (self.y - 0) * (self.y - 0)) - self.r))
def __getattr__(self, name):
print("===== get:", 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("===== set:", name, value)
if name in ['x', 'y']:
if isinstance(value, int):
print('we can set x,y')
super().__setattr__(name, value) # mod : better
else: # value isn't an int
raise TypeError('Expected an int')
elif name in ['r', 'area', 'circumference', 'distance_to_origin']: # mod : add 'r'
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])
'''