类实例存储在数组中时如何访问类变量

2024-07-04 08:11:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始用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

Tags: 实例self程序objthatdefrandom数组
1条回答
网友
1楼 · 发布于 2024-07-04 08:11:28

问题是您需要实际实例化对象,否则__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"

相关问题 更多 >

    热门问题