class – Python calling method without self

class – Python calling method without self

Also you can make methods in class static so no need for self. However, use this if you really need that.

Yours:

class bla:
    def hello(self):
        self.thing()

    def thing(self):
        print hello

static edition:

class bla:
    @staticmethod
    def hello():
        bla.thing()

    @staticmethod
    def thing():
        print hello

One reason is to refer to the method of that particular classs instance within which the code is be executed.

This example might help:

def hello():
    print global hello

class bla:
    def hello(self):
        self.thing()
        hello()

    def thing(self):
        print hello

b = bla()
b.hello()
>>> hello
global hello

You can think of it, for now, to be namespace resolution.

class – Python calling method without self

The short answer is because you can def thing(args) as a global function, or as a method of another class. Take this (horrible) example:

def thing(args):
    print Please dont do this.

class foo:
    def thing(self,args):
        print No, really. Dont ever do this.

class bar:
    def thing(self,args):
        print This is completely unrelated.

This is bad. Dont do this. But if you did, you could call thing(args) and something would happen. This can potentially be a good thing if you plan accordingly:

class Person:
    def bio(self):
        print Im a person!

class Student(Person):
    def bio(self):
        Person.bio(self)
        print Im studying %s % self.major

The above code makes it so that if you create an object of Student class and call bio, itll do all the stuff that would have happened if it was of Person class that had its own bio called and itll do its own thing afterwards.

This gets into inheritance and some other stuff you might not have seen yet, but look forward to it.

Leave a Reply

Your email address will not be published. Required fields are marked *