def f(obj):
print('attr =', obj.attr)
class Foo:
attr =100
attr_val=f
x =Foo()
print(x.attr)
x.attr_val()
100
attr=100
I got this code from real python but I don't understand how x is pass into function f. Can someone explain that to me thanks
CodePudding user response:
x
is a class object when you are doing x.attr_val()
it automatically takes itself and provides it as a first argument to the function (often arguments like this are named self
).
CodePudding user response:
In python doc:
Any function object that is a class attribute defines a method for instances of that class.
https://docs.python.org/3/tutorial/classes.html#random-remarks
That is, when you call the class attribute attr_val
(which is f
; note that attr_val
is not an instance attribute), it is designed to supply the instance x
(not the class).
CodePudding user response:
attr_val
is what is called an instance method. When your Foo
class calls it, it passes the object as first argument automatically, effectively running: f(x)
If you were using a custom __init__
method, the standard practice would be to pass the self
variable to indicate this self-reference.
Thus, a more verbose variant would be:
def f(obj):
print('attr =', obj.attr)
class Foo:
def __init__(self):
self.attr = 100
def attr_val(self):
f(self) # or "return f(self)"
x = Foo()
x.attr_val()
# attr = 100