(Python 2.7)我试图从SierpinskiTriangle类访问vertices变量,并在列出的第二行代码中使用它,但它显示
TypeError:“属性”对象不可迭代
我只能假定这是由于访问者/更改者
基本代码:
class Fractal(object):
# the constructor
def __init__(self, dimensions):
# the canvas dimensions
self.dimensions = dimensions
# the default number of points to plot is 50,000
self.num_points = 50000
# the default distance ratio is 0.5 (halfway)
self.r = 0.5
# accessors and mutators
@property
def vertices(self):
return self._vertices
@vertices.setter
def vertices(self, v):
self._vertices = v
class SierpinskiTriangle(Fractal):
# the constructor
def __init__(self, canvas):
# call the constructor in the superclass
Fractal.__init__(self, canvas)
# define the vertices based on the fractal size
v1 = Point(self.dimensions["mid_x"], self.dimensions["min_y"])
v2 = Point(self.dimensions["min_x"], self.dimensions["max_y"])
v3 = Point(self.dimensions["max_x"], self.dimensions["max_y"])
self.vertices = [ v1, v2, v3 ]
获取顶点的代码:
class ChaosGame(Canvas):
vertex_radius = 2
vertex_color = "red"
point_radius = 0
point_color = "black"
def __init__(self, master):
Canvas.__init__(self, master, bg = "white")
self.pack(fill = BOTH, expand = 1)
# a function that takes a string that represents the fractal to create
def make(self, f):
if f == "SierpinskiTriangle":
vertices = SierpinskiTriangle.vertices
if f == "SierpinskiCarpet":
vertices = []
if f == "Pentagon":
vertices = []
if f == "Hexagon":
vertices = []
if f == "Octagon":
vertices = []
print vertices
for point in vertices:
self.plot_point(self, point, ChaosGame.vertex_color, ChaosGame.vertex_radius)
答案 0 :(得分:2)
这是因为您正在访问类而不是该类型的对象。
让我们尝试一个最小的例子:
class Container:
def __init__(self):
self._content = range(10)
@property
def content(self):
return self._content
@content.setter
def set_content(self, c):
self._content = c
这有效:
c = Container()
for number in c.content:
print(number)
(打印出0到9之间的数字)。
但这失败了:
for number in Container.content:
print(number)
错误
TypeError Traceback (most recent call last)
<ipython-input-27-f1df89781355> in <module>()
1 # This doesn't:
----> 2 for number in Container.content:
3 print(number)
TypeError: 'property' object is not iterable
除了属性问题之外,您没有初始化对象,因此从未调用类的__init__
函数,也未初始化Container._content
。
实际上,如果您刚刚使用过,也会遇到类似的问题
class Container:
def __init__(self):
self.container = range(10)
(仅在这种情况下将是属性错误)。 最后说明:这
for number in Container().content: # note the '()'!!
print(number)
再次起作用,因为我们正在动态创建一个容器对象。