1

In Learn Python The Hard Way exercise 43, there is a list in the class called quips

class Death(Scene):

    quips = [
        "You died.  You kinda suck at this.",
         "Your mom would be proud...if she were smarter.",
         "Such a luser.",
         "I have a small puppy that's better at this."
    ]

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

Why isn't it assigned to self? I can't get my head around an explanation I saw on Reddit:

"Note the lack of any reference to self? That means that there's no instance involved. This is an attribute of the class. It's like writing on the blueprint instead of on the wall of your house. The class/blueprint "owns" the quips attribute. The attribute is an otherwise uninteresting list object. Because of the name resolution, instances can refer to this object as well: "

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
Raz
  • 93
  • 1
  • 6
  • 3
    Try to learn Python _the easy way_ :) – ForceBru Mar 28 '15 at 13:00
  • 2
    please make sure the class code is transcribed and displayed above as it shows in the example your doubt is. As it is one can't know what the original code is. – jsbueno Mar 28 '15 at 13:01
  • 2
    `quips` is a **class attribute**, which is shared by all instances of the class. [Python: Difference between class and instance attributes](http://stackoverflow.com/q/207000/4014959) discusses this topic. – PM 2Ring Mar 28 '15 at 13:06
  • 1
    Please note the example is rather confusing: I see both `Death.quips` and `self.quips`. Both are valid, and will ultimately refer to the same object in that particular case as in Python `self.quips` will first look for an instance field named `quips` and then, if not found, for a class member of the same name. Learn Python _really_ the hard way... – Sylvain Leroux Mar 28 '15 at 13:22

2 Answers2

2

The list, Death.quips, is a member of the class itself, not of some instance of the class. Since there is no instance involved, there is also no self mentioned in the definition.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Just so you know you can access the list with both self.quips and Death.quips. Let's say you live in your mom's basement. Whatever it is that may be down there, is it really yours? Nope but you still have access to it. Both you and your mom both can access the basement, but it actually belongs to your mom. Likewise, both the instance object and class can access the list, when it belongs to class.

Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70