Why is the class passed to a function being called inside a class function when using self in Python? -


so, have code snippet.

class logobserver(object):      def write_log(...):         self.logger.log(self, level, message, *args, **kwargs) ... 

looking debugger , error messages well, noticed variable level contains logobserver instead of integer. expecting integer.

however, when remove self self.logger.log() like:

self.logger.log(level, message, *args, **kwargs) 

level contains integer instead of logobserver object. error messages disappear well.

what explanation behind behavior?

if call instance method (not staticmethod or classmethod), instance implicitly passed first parameter. why method definitions take self first parameter; name self convention, way. example, foo.bar() translated type(foo).bar(foo).

if explicitly pass on instance argument, passed along other argument - after instance passed in implicitly already. example, foo.bar(foo) translated type(foo).bar(foo, foo).

now, inside method, self first parameter. let's have defined

class foo(object):   def bar(self, other=none):     pass foo = foo() 

calling foo.bar() translated type(foo).bar(self=foo, other=none). likewise, foo.bar(foo) translated type(foo).bar(self=foo, other=foo).

so, when call self.logger.log(self, level, message, *args, **kwargs), translates type(self).logger.log(self=self, level=self, message=level, args=(message,), kwargs={}). thus, level gets instance of object, namely self.


note foo.bar() not resolved type(foo).bar(foo) - case if bar defined on class/type. passing of self not changed this, however.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -