开发者

Superfluous python parameters

I've noticed a discrepancy in the way that python parameters are called. In every other language I've dealt with, you either have

foo() 

meaning either no parameters, or as many parameters as you like, or

foo(arg1, arg2,...,argn)

where you pass in the same number of 开发者_开发百科parameters to define the function and call it. In python however, I've noticed that the function definitions, and when the function is called, can have two different parameters sets, this usually consists of:

class foo(object):
    def bar(self, arg1, arg2):
        pass

However, when I want to call the function, all I have to do is:

zoo = foo()
zoo.bar(arg1, arg2)

Where did the self parameter go?

Thank you.


Where did the self parameter go?

It's in front of the dot when you call the function, i.e. in your case it's zoo.

Note that you can also call the function as foo.bar(zoo, arg1, arg2). Basically in python object.method(arguments) is a shortcut for objects_class.method(object, arguments).


zoo is the self parameter.

In C++, for example, you get the object passed implicitly as the this pointer. In Python, this parameter is explicit.


zoo is implicitly passed as the first parameter in your example.


As I remember, "zoo.bar" gives you just an attribute "bar" of object "zoo" that can be called. All magic is done at construction where all methods of class is binded to that object while dictionary of attributes is populated. Consider next example:

zoo = foo()
xbar = zoo.bar
xbar(arg1, arg2)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜