(Python 2.7)使用访问器/赋值器访问类中的变量



(Python 2.7(我试图从SierpinskiTriangle类访问顶点变量,并在列出的第二位代码中使用它,但它显示

TypeError:"property"对象不是可迭代的

我只能假设这是由于访问者/突变体

基本代码:

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)

这是因为您访问的是类而不是该类型的对象。

让我们在一个最小的例子上试试:

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)

再次工作,因为我们在运行中创建了一个容器对象。

最新更新