0
Function Attribute (Python)
In Python function can have attribute as it is also a Object. Does it mean that local variable defined inside function will also be considered as attribute of that function? Or it have completely different scope. Eg. def fun(): check = "OK" return check print(fun.check) #Error print(fun()) #OK fun.check = "KO" print(fun.check) #KO print(fun()) #OK https://code.sololearn.com/cD4l4eW9IJh0/?ref=app
5 Respuestas
+ 3
It wouldn't be an attribute, itd be a local variable that loses reference as soon as the function is complete. You can reference an attribute without running the function.
+ 3
Slick Here's my vague interpretation of the working of Python functions:
def foo():
a = [*range(1, 101)]
print(", ".join(map(str, a)))
return a[-4]
'foo' is a function object and the code contents inside this function is stored as a string attribute (say, 'data' here):
foo.data = """a = [*range(1, 101)]
print(", ".join(map(str, a)))
return a[-4]"""
And this one is executed, with certain obvious differences as compared to the normal execution of code. Am I getting it right?
+ 1
Slick Well right! I see that those local variable are not getting listed inside fun attribute. In Django this thing is useful for catching.
+ 1
Slick I'm not sure if I'm getting it right, but that's the only possibility that I see. But I don't see any such suspicious attributes when I use the dir() function that holds the id to the code as a string.
0
I like the thought process, i just don't quite understand the question Delicate Cat. You can run either of those, the actual code or a string of code using eval(). I also don't get why use attributes in small functions when we could just havelocal variables or global attributes in a class that we reference inside a method.