Python函数可以给出从范围之外的新的属性? [英] Python functions can be given new attributes from outside the scope?

查看:188
本文介绍了Python函数可以给出从范围之外的新的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道你可以这样做:

I didn't know you could do this:

def tom():
    print "tom's locals: ", locals()

def dick(z):
    print "z.__name__ = ", z.__name__
    z.guest = "Harry"
    print "z.guest = ", z.guest
    print "dick's locals: ", locals()

tom()              #>>> tom's locals:  {}
#print tom.guest    #AttributeError: 'function' object has no attribute 'guest'
print "tom's dir:", dir(tom)  # no 'guest' entry

dick( tom)         #>>> z.__name__ =  tom
                   #>>> z.guest =  Harry
                   #>>> dick's locals:  {'z': <function tom at 0x02819F30>}
tom()              #>>> tom's locals:  {}
#print dick.guest  #AttributeError: 'function' object has no attribute 'guest'

print tom.guest    #>>> Harry
print "tom's dir:", dir(tom)  # 'guest' entry appears

功能汤姆()没有本地人。功能迪克()知道哪里汤姆()的生活和飞架哈利汤姆'客人'在()的地方。哈利没有出现在汤姆本地()的地方,但如果你问汤姆的客人,哈里回答。哈利是汤姆一个新属性()。

Function tom() has no locals. Function dick() knows where tom() lives and puts up Harry as 'guest' over at tom()'s place. harry doesn't appear as a local at tom()'s place, but if you ask for tom's guest, harry answers. harry is a new attribute at tom().

更新:从外汤姆(),你可以说打印目录(TOM),并看到了TOM-对象的字典。 (您可以做到这一点的汤姆()了。所以汤姆可以找出他有一个新的房客,哈利的'客人'的名义去。)

UPDATE: From outside tom(), you can say "print dir(tom)" and see the the tom-object's dictionary. (You can do it from inside tom(), too. So tom could find out he had a new lodger, harry, going under the name of 'guest'.)

所以,属性可以从功能之外增加一个函数的名字空间?那是经常做?它是可以接受的做法?难道在某些情况下建议?它是在时间实际上非常重要? (它是Python的?)

So, attributes can be added to a function's namespace from outside the function? Is that often done? Is it acceptable practice? Is it recommended in some situations? Is it actually vital at times? (Is it Pythonic?)

更新:标题现在说'属性';它曾经说'变量'。这里有一个 PEP有关函数属性

UPDATE: Title now says 'attributes'; it used to say 'variables'. Here's a PEP about Function Attributes.

推荐答案

@behindthefall,给函数的动机对象一般可分配属性(他们没有使用让他们)是,如果没有这样的可能性,真正的和流行的框架被滥用一些什么属性分配的存在(典型值 __ __ DOC )来记录每一个给定的函数对象的信息。所以,显然有被压抑的需求这一功能,所以圭多决定直接解决这个问题(添加一个可选的字典以每个函数对象来记录它的属性是不是一个大问题 - 大多数函数对象并不需要它,它的可选的,所以成本是一个空指针仅有4个字节; - )

@behindthefall, the motivation to give function objects generic assignable attributes (they didn't use to have them) was that, absent such possibilities, real and popular frameworks were abusing what few assignable attributes existed (typically __doc__) to record information about each given function object. So there was clearly a "pent-up demand" for this functionality, so Guido decided to address it directly (adding an optional dict to each function object to record its attributes isn't a big deal -- most function objects don't need it, and it is optional, so the cost is just 4 bytes for a null pointer;-).

在指定任意的地方这样的属性将是非常不好的做法,使得code更难理解为没有真正的好处,但在可控的方式使用时,他们非常有用 - 例如,一个装饰可以有效记录各种有关功能的东西被装饰,并且在其中发生装饰的背景下,作为包装函数的属性,允许这样的元数据的平凡易内省随时以后发生,根据需要

Assigning such attributes in arbitrary places would be very bad practice, making the code harder to understand for no real benefit, but they're very useful when used in a controlled way -- for example, a decorator could usefully record all kinds of things about the function being decorated, and the context in which the decoration occurred, as attributes of the wrapper function, allowing trivially-easy introspection of such metadata to occur later at any time, as needed.

至于其他的答案已经指出的那样,局部变量(这是每个实例,不是每个函数对象!)是在其 __字典__

As other answers already pointed out, local variables (which are per-instance, not per-function object!) are a completely disjoint namespace from a function object's attributes held in its __dict__.

这篇关于Python函数可以给出从范围之外的新的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆