开发者

what is this code mean in python,

def a():
    print 'sss'

print getattr(a, "_decorated_function", a).__name__

it print :

a

thanks

updated

my cod开发者_StackOverflowe:

def a():
    w='www'

print getattr(a,'w')

but it print :

Traceback (most recent call last):
  File "D:\zjm_code\a.py", line 8, in <module>
    print getattr(a,'w')
AttributeError: 'function' object has no attribute 'w'


See the documentation for getattr in Python. The reason it is printing "a", is because "a" has no attribute named "_decorated_function", and the third parameter to getattr() is a default value to return in the event that the first parameter has no attribute with the name of the second parameter. So, your code is the same as:

print a.__name__

Not suprisingly, a's name is "a", hence you get that as the output. By the way, I strongly suggest that you search the Python documentation prior to posting questions here on StackOverflow, as you are more likely to get answers there sooner. You might also find my Development and Coding Search custom search engine useful in finding the relevant Python reference documentation for future queries.


In response to the Updated question

Functions must be given their attributes after declaration.

def a():
    pass

a.w = 'www'
print a.w

Another method that is more similar with other OO languages is to use a class. This example will make a static attribute:

class a:
    w = 'www'

print a.w

This will make w shared between all instances of class a, which is most useful as a constant in the program. If you on the other will be working with the variable and changing its value, it it better to do the following:

class b:
    def __init__(self):
        self.w = 'www'

c = b()
print c.w


If a has an attribute called _decorated_function then it returns what that attribute contains, otherwise it returns a. Seriously, this is all in the docs.


I'll take a guess:

The code can be broken into 2 steps:

func = getattr(a, "_decorated_function", a)
print func.__name__

Ignore the first line.

The second line prints the name of func, which in your case happens to be 'a'. No surprise.

The first line is there for the case of decorators:

class My_decorator:
    def __init__(self,func):
        self._decorated_function = func
    def __call__(self,arg):
        self._decorated_function(arg+1)

@My_decorator
def a(i):
    print i

print a(0)
>>> 1

print a._decorated_function.__name__
>>> a

So the objects that you will be calling getattr(a, "_decorated_function", a) are expected to be either functions, or classes that have "decorated" a function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜