<pre><code>class t(dict):
def __init__(self, **kwargs):
for key, value in kwargs.items():
dict.__setitem__(self, key, value)
def __getattr__(self, key):
return dict.__getitem__(self, key)
def __setattr__(self, key, value):
raise StandardError("Cannot set attributes of tuple")
def __setitem__(self, key, value):
raise StandardError("Cannot set attributes of tuple")
def __delitem__(self, key):
raise StandardError("Cannot delete attributes of tuple")
point = t(x=10, y=500, z=-50)
print point.x # 10
print point.y # 500
print point['z'] # -50
print point # {'z': -50, 'y': 500, 'x': 10}
point.x = 100 # StandardError: cannot set attributes of tuple
point.y += 5 # StandardError: cannot set attributes of tuple
point.z = -1 # StandardError: cannot set attributes of tuple
def hypo(x, y, z):
return (x**2 + y**2 + z**2)**0.5
print hypo(point) # TypeError: unsupported operand type(s)
print hypo(**point) # 502.593274925
for k in point.items():
print k # ('y', 500)
# ('x', 10)
# ('z', -50)
for k in point.keys():
print k # x
# y
# z
for k in point.values():
print k # 500
# 10
# -50
print len(point) # 3
print dict(point) # {'y': 500, 'x': 10, 'z': -50}
</code></pre>
<p>这是我解决这个问题的办法。优美的语法,不可更改(至少不需要借助于某个讨厌的对象。<strong>setattr</strong>)体操,轻巧且可打印。尽管这件事你做不到,但你也不能用一个口述词</p>
<pre><code>point = t(x=10, y=20, z=30)
d = point.x ** 2 + point.y ** 2 + point.z ** 2
</code></pre>
<p>与…有很好的对称性</p>
<pre><code>point = (10, 20, 30)
d = point[0] ** 2 + point[1] ** 2 + point[2] ** 2
</code></pre>
<p>总的来说</p>
<pre><code>point = {'x': 10, 'y': 20, 'z': 30}
d = point['x'] ** 2 + point['y'] ** 2 + point['z'] ** 2
</code></pre>