簡體   English   中英

為什么在這種情況下需要使用引用而不是使用self?

[英]Why do I need to call 'quotes' in this scenario as opposed to using self?

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)

好的,我是編程新手,正在通過制作基於文本的游戲學習類的使用,但是我不確定為什么使用Death.quips代替self.quips,或者為什么不使用death.quips self.quips。 我認為這與本地引用有關,但我不知道為什么您必須在特定情況下使用它們。 謝謝!

quotes是一個類變量,而不是實例變量。 如果它是一個實例變量,則可以使用

self.quotes = [...]

並且需要在提供self參數的方法內進行設置(如您的enter方法所示)

使用ClassName.variable訪問類變量,而通過self.variable訪問類中的實例變量。

可以在此處找到對此的良好參考: http : //timothyawiseman.wordpress.com/2012/10/06/class-and-instance-variables-in-python-2-7/

假設quips是指您實際上可以使用任何一個quotes ,但是它們的影響略有不同。

如果使用Death.quotes它將在Death類中查找名為quotes的屬性,並將使用它。

如果您使用self.quotes這將首先您的實例內尋找self ,然后你的類實例的內部self為屬性叫做quotes 在您的特定示例中,此行為與調用Death.quotes相同,因為selfDeath類的實例,但是您應該注意一些關鍵區別:

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 ,但是了解原因很重要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM