为什么我需要在这个场景中调用'quotes',而不是使用self?

2024-10-02 14:25:25 发布

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

class Death(Scene):

     quotes = [
          "You are dead.",
          "Haha. bad.",
          "Sorry, you died.",
          "Probably should try something different."
          ]

     def enter(self):
          print Death.quotes[randint(0, len(self.quips)-1)]
          exit(1)

好吧,我对编程还很陌生,正在通过制作一个基于文本的游戏来学习类的使用,但是我不知道为什么死亡。俏皮话是用来代替自嘲,或者更确切地说是为什么死亡。俏皮话不使用而不是自嘲. 我认为这与当地人对俏皮话的引用有关,但我不知道为什么你必须在特定的情况下使用每一种。谢谢!你知道吗


Tags: selfyousceneareclassquotesbaddead
2条回答

假设你所说的quips是指quotes,你实际上可以使用其中任何一种,但它们的效果略有不同。你知道吗

如果您使用Death.quotes,这将在类Death中查找名为quotes的属性并使用它。你知道吗

如果您使用self.quotes,这将首先在实例self内查找,然后在实例self的类内查找名为quotes的属性。在您的特定示例中,这与调用Death.quotes的行为相同,因为self是类Death的一个实例,但是有一些关键的区别您应该注意:

1)如果您的实例变量self也有一个名为quotes的属性,那么它将被访问,而不是使用与以下示例相同的名称访问class属性:

class Death(Scene):
    quotes = [
        'some awesome quote',
    ]
    def __init__(self):
        sef.quotes = ['foo']

    def some_method(self):
        # This will print out 'some awesome quote'
        print Death.quotes[0]
        # This will print out 'foo'
        print self.quotes[0]

2)如果selfDeath的子类的实例,并且该子类定义了它自己的类变量名quotes,那么使用self.quotes将使用attribute,如下面的示例所示。你知道吗

class Death(Scene):
    quotes = [
        'some awesome quote',
    ]
    def some_method(self):
        print self.quotes[0]

class DeathChild(Death):
    quotes = [
        'not so awesome quote'
    ]

instance1 = Death()
instance2 = DeathChild()

# This will print out 'some awesome quote'
instance1.some_method()
# This will print out 'not so awesome quote'
instance2.some_method()

既然您已经了解了这一点,我将告诉您,通过子类化支持扩展实际上(通常)是一件好事,我自己也会使用self.quotes而不是Death.quotes,但了解原因很重要。你知道吗

quotes是类变量,而不是实例变量。如果它是一个实例变量,那么应该使用

self.quotes = [...]

需要在提供self参数的方法内设置(如enter方法所示)

类变量使用ClassName.variable访问,而类内的实例变量则通过self.variable访问。你知道吗

这里有一个很好的参考:http://timothyawiseman.wordpress.com/2012/10/06/class-and-instance-variables-in-python-2-7/

相关问题 更多 >