[英]How to call a function stored in a Python class instance variable
I'm passing a function as a parameter to a class constructor. 我正在将函数作为参数传递给类构造函数。 The constructor stores it in an instance variable, and other class methods want to call it. 构造函数将其存储在实例变量中,其他类方法希望对其进行调用。
class ComboList(list) :
def __init__(self,a,b,kg) :
list.__init__(self)
self.__kg = kg
# More stuff follows
When I try to call the function in another method, for example: 当我尝试以其他方法调用该函数时,例如:
x = self.__kg('a')
I get "{AttributeError}'' object has no attribute '__kg'." 我得到“ {AttributeError}”对象没有属性“ __kg”。
When I evaluate the function call in my IDE's Evaluate Expression window, I get the same thing. 当我在IDE的“评估表达式”窗口中评估函数调用时,会得到相同的结果。 But when I evaluate the instance variable itself ("self.__kg"), I get: 但是,当我评估实例变量本身(“ self .__ kg”)时,我得到:
result = {function} <function <lambda> at 0x0000000002ED5C18>
...so it appears that the attribute __kg is defined. ...因此似乎已定义了__kg属性。
What is going wrong? 怎么了?
I can call the function by referencing the parameter -- no problem. 我可以通过引用参数来调用函数-没问题。
kg(a')
I can also assign the parameter's value to a method variable and call the variable -- no problem. 我还可以将参数的值分配给方法变量,然后调用该变量-没问题。
_kag = kg
_kag('a')
It's only the reference to the instance variable that doesn't work. 只是对实例变量的引用无效。
Whenever a variable has a double underscore in a class, Python will invoke name mangling (see the Python documentation on classes ). 每当变量在类中具有双下划线时,Python就会调用名称修饰(请参阅有关类的Python文档 )。 Using double underscores is pretty much only to avoid name clashes with subclasses or to make a variable 'really private'. 使用双下划线几乎只是为了避免名称与子类冲突或使变量“真正私有”。 (See PEP8 for more style suggestions). (有关更多样式建议,请参见PEP8 )。
If you want other inherited subclasses to use your private variable, you can either use one single underscore ( _kg
) or use the @property
decorator. 如果你想其他遗传子类来使用你的私有变量,你可以使用一个单一的下划线( _kg
),或使用@property
装饰。
Check out this really dumb example: 看看这个非常愚蠢的例子:
class ComboList(list) :
def __init__(self,a,b,kg) :
list.__init__(self)
self.__kg = kg
# More stuff follows
@property
def kg(self):
return(self.__kg)
my_list = ComboList(1,2,'This will be printed')
print(my_list.kg)
Don't use double underscore, which makes python do some magic and append classname to variable names (called name mangling). 不要使用双下划线,这会使python做一些魔术,并将类名附加到变量名下(称为名称改写)。 Just use single underscore instead of double. 只需使用下划线而不是双下划线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.