如何从类方法中调用全局函数 [英] How to call global function from class method
问题描述
我有以下代码:
def __static_func(name):
print 'Name = ' + name
class A:
def __init__(self, name):
self.name = name
def fun(self):
__static_func(self.name)
a = A('foo')
a.fun()
在Python 2.7上启动时,它会产生
When launched on Python 2.7, it produces
NameError: global name '_A__static_func' is not defined
所以问题是如何从类方法中调用全局函数?
So the question is how do I call global function from within class method?
推荐答案
我最近正在读一本书 O'Reilly学习Python (第944页,第31章),提到使用双下划线 __
作为方法的起始字符或 Class
中的变量,它会自动将 _classname
附加到该函数e classname
是类名。这样做是为了将名称本地化为它所属的类。在伪私有类属性的上下文中,这称为名称处理。
I was recently reading a book "Learning Python by O'Reilly" (Page 944, Chapter 31) and it was mentioned that when you use double underscores __
as the starting characters of a method or a variable in the Class
, it automatically appends the _classname
to that function where classname
is the class name. This is done to localize a name to the class to which it belongs. This is called Name Mangling in the context of Pseudoprivate class attributes.
这样,您可以在两个不同的类 A 中使用相同的名称
和 __ variable
B
,因为变量/方法将私有化为 _A__variable
和 _B__variable
。因此,只需用单个下划线为全局函数命名,以免发生这种冲突。
This way you can use the same name __variable
in two different classes A
and B
as the variables/methods will become privately _A__variable
and _B__variable
respectively. So just name your global function something else with a single underscore for example to avoid this conflict.
这篇关于如何从类方法中调用全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!