Home > Software engineering >  Name self is not defined, but I thought it was?
Name self is not defined, but I thought it was?

Time:11-28

I receive the error "NameError: name '_Activity__self' is not defined". I used self as a parameter in everything and for the members so I'm not sure what I'm missing. -- I'm trying to have Activity be the parent class and WakeUp be derived from Activity.

class Activity:

        def __init__ (self, d, t):
                __self.date = d
                __self.time = t

        def getDate(self):
                return self.date

        def getTime(self):
                return self.time


class WakeUp (Activity):

        def __init__ (self, d, t):
                Activity.__init__(self, d, t)
                __self.activityType = "WakeUp"

        def getType(self):
                return self.activityType

CodePudding user response:

You are using __self instead of self.
This should work
.

class Activity:

        def __init__ (self, d, t):
                self.date = d
                self.time = t

        def getDate(self):
                return self.date

        def getTime(self):
                return self.time


class WakeUp (Activity):

        def __init__ (self, d, t):
                Activity.__init__(self, d, t)
                self.activityType = "WakeUp"

        def getType(self):
                return self.activityType

CodePudding user response:

__self would work if __self was in the tuple, eg (__self, d, t). Note that the first parameter in the 'init' tuple determines the 'self' name for the class. Convention recommends `self' but in fact it can be anything you want. It is the position in the parameters tht is important.

Check out 'What is self' in https://docs.python.org/3/faq/programming.html?highlight=self#what-is-self

  • Related