Getting None type for object when running method outside of __init__

473 Views Asked by At

For the following class

class Member(object):
    def __init__(self, fields, scouts, id):
        self.id = id
        self.fields = fields
        self.scouts = scouts
        self.routes = [Route(s) for s in self.scouts ]
        self.routeBreak = []
        self.numScouts = len(self.scouts)

I run this method

def createMember(self):    
    random.shuffle(self.fields)
    self.routeBreak = self.createBreaks(len(self.fields))
    self.assignRoutes()

Example:

Member.createMember()

However, after doing so, the object Member comes back as "None". I tried adding createMember() to the init method

class Member(object):
    def __init__(self, fields, scouts, id):
        self.id = id
        self.fields = fields
        self.scouts = scouts
        self.routes = [Route(s) for s in self.scouts ]
        self.routeBreak = []
        self.numScouts = len(self.scouts)
        random.shuffle(self.fields)
        self.routeBreak = self.createBreaks(len(self.fields))
        self.assignRoutes()

And then everything is fine. I can run my other methods on the object no problem. I have no idea why this is happening and I need to figure out how to run createMember() outside of the init method. I am fairly new to using Classes and Methods so any explanation would be helpful. Thanks!

2

There are 2 best solutions below

1
On BEST ANSWER

Expanding on Tim's question, when using classes, you have the class definition, a type, and then an instance of the class, the object.

createMember should be called as a method of an instance, not of the class itself (there is a type for that - a staticmethod or classmethod, and they do not have a "self").

So you need to create the instance:

m = Member()

Note - you will need the parameters to do that. If you want it to not need the parameters, that requires a bit more code. Then access that method in it:

m.createMember()

You could also call it inside _init__ (known as the constructor), where "self" is the instance:

self.createMember()
0
On

As createMember needs an argument self which should be the instance itself, you can't call it by Member.createMember() because this makes it a unbound method without Member instance as the required argument. Member is a class not an instance. You have to call it by Member.createMember(memberInstance) to explicitly provide the instance itself.

Member().createMember() doesn't need to give the argument is because Member() has created an instance which will implicitly serves as the first argument self.