Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call global function from class method

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?

like image 753
Nick Avatar asked Oct 17 '18 11:10

Nick


2 Answers

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.

like image 163
Sheldore Avatar answered Sep 21 '22 20:09

Sheldore


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

like image 41
Phillip Avatar answered Sep 20 '22 20:09

Phillip