I have the following code:
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()
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?
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.
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.
Don't use double underscores.
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()
Should work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With