Python calling method without 'self'

≡放荡痞女 提交于 2019-12-03 04:21:18

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 class's 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.

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 don't do this."

class foo:
    def thing(self,args):
        print "No, really. Don't ever do this."

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

This is bad. Don't 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 "I'm a person!"

class Student(Person):
    def bio(self):
        Person.bio(self)
        print "I'm studying %s" % self.major

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

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

There might be another function with the same name outside your class. self is an object reference to the object itself, therefore, they are same. Python methods are not called in the context of the object itself. self in Python may be used to deal with custom object models or something.

To me, self like a scope definer, with self.foo() and self.bar indicating the function and the parameter defined in the class and not those defines in the other places.

A mirror reflects the difference with java and python: java could use method within class without self because the only way to call a method is from class or obj, so the way is clear to compiler. While this may confuse the translator of python and consumes significant time to look up the symbol table over the whole name space in running time, because both function and class method are the potential candidates for a function call given the 'self' is not used. If this practice is used, the python speed would once again slowed down compared to C and Java which could make it less attractive.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!