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)
好吧,我对编程还很陌生,正在通过制作一个基于文本的游戏来学习类的使用,但是我不知道为什么死亡。俏皮话是用来代替自嘲,或者更确切地说是为什么死亡。俏皮话不使用而不是自嘲. 我认为这与当地人对俏皮话的引用有关,但我不知道为什么你必须在特定的情况下使用每一种。谢谢!你知道吗
假设你所说的
quips
是指quotes
,你实际上可以使用其中任何一种,但它们的效果略有不同。你知道吗如果您使用
Death.quotes
,这将在类Death
中查找名为quotes
的属性并使用它。你知道吗如果您使用
self.quotes
,这将首先在实例self
内查找,然后在实例self
的类内查找名为quotes
的属性。在您的特定示例中,这与调用Death.quotes
的行为相同,因为self
是类Death
的一个实例,但是有一些关键的区别您应该注意:1)如果您的实例变量
self
也有一个名为quotes
的属性,那么它将被访问,而不是使用与以下示例相同的名称访问class属性:2)如果
self
是Death
的子类的实例,并且该子类定义了它自己的类变量名quotes
,那么使用self.quotes
将使用attribute,如下面的示例所示。你知道吗既然您已经了解了这一点,我将告诉您,通过子类化支持扩展实际上(通常)是一件好事,我自己也会使用
self.quotes
而不是Death.quotes
,但了解原因很重要。你知道吗quotes
是类变量,而不是实例变量。如果它是一个实例变量,那么应该使用需要在提供
self
参数的方法内设置(如enter
方法所示)类变量使用
ClassName.variable
访问,而类内的实例变量则通过self.variable
访问。你知道吗这里有一个很好的参考:http://timothyawiseman.wordpress.com/2012/10/06/class-and-instance-variables-in-python-2-7/
相关问题 更多 >
编程相关推荐