What does the Python error “name 'self' is not defined” mean?

前端 未结 4 1819
心在旅途
心在旅途 2021-01-13 17:32

I can\'t figure out what\'s wrong with this very simple snippet:

class A(object):
        def printme(self):
                print \"A\"

        self.printm         


        
4条回答
  •  暖寄归人
    2021-01-13 18:05

    The following should explain the problem. Maybe you will want to try this?

    class A(object):
        def printme(self):
            print "A"
    a = A()
    a.printme()
    

    The name self is only defined inside methods that explicitly declare a parameter called self. It is not defined at the class scope.

    The class scope is executed only once, at class definition time. "Calling" the class with A() calls it's constructor __init__() instead. So maybe you actually want this:

    class A(object):
        def __init__(self):
            self.printme()
        def printme(self):
            print "A"
    a = A()
    

提交回复
热议问题