Why Can Instance Methods Be Called As Class Methods In Python 3?
Solution 1:
On Python 3, Foo.bar
is just that bar
function you wrote. It takes one parameter, which happens to be named self
, and prints it. You can call that function on anything, and it will print whatever argument you pass it.
On Python 2, Foo.bar
isn't quite the bar
function you wrote. When you access Foo.bar
, Python generates an unbound method object wrapping the bar
function. The unbound method object works mostly like the bar
function, with the main difference of validating that its first argument is an instance of Foo
. You could do
Foo.bar(some_foo_instance)
which would work like some_foo_instance.bar()
, but calling Foo
's implementation, bypassing any overrides in subclasses. You couldn't do Foo.bar('hello')
, though.
Python 3 removed unbound method objects. They don't exist any more. That makes the language a bit simpler, but it removes the validation unbound method objects used to perform.
Post a Comment for "Why Can Instance Methods Be Called As Class Methods In Python 3?"