'Can some one explain how x pass into function f
def f(obj):
print('attr =', obj.attr)
class Foo:
attr = 100
attr_val = f
x = Foo()
print(x.attr)
x.attr_val()
Output:
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.
Solution 1:[1]
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).
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Í›Ì͔̲̲̑̑̒̅ͅ ̴͈̮͉͉͛̀̒͋̒ ̲̎̅̽̑̀̿ |
| Solution 2 |
