我开始使用 python 进行面向对象编程,在我的程序中,我决定将类实例存储在数组中,但我现在不知道如何访问类变量。
class apixel(object):
def __init__(self):
self.posx = random.randint(0, 300)
self.posy = random.randint(0, 200)
def do_i_exist():
print("Yes i do!")
p = [apixel] * 10
for obj in p:
obj.do_i_exist() #that works
print(obj.posx) #but that does not work
请您参考如下方法:
问题是您需要实际实例化对象,否则永远不会调用 __init__。
尝试:
p = [apixel() for _ in range(10)]
根据下面 Craig 的评论,列表理解调用构造函数 10 次,因此您获得 10 个独立的对象。
但是,您的 apixel 没有 self.posx 的原因是您的代码从未调用构造函数。您不是在创建类的实例列表,而是对类定义的引用列表。
根据 DanielPryden 对您的 OP 的评论,您应该更改 do_i_exist 方法的签名以接受 self,或者将其注释为 static :
# as an instance method, which requires "self":
do_i_exist(self):
...
# as a static class method that is the same for all instances:
@staticmethod
do_i_exist():
... method body contains NO references to "self"
