+ 2

call private class function in exec() python

I am having an unexpected issue. This is the simplified code: class test(): def __init__(self,name): self.name = name def __private(self): print(self.name) def public(self): exec("self.__private()") obj = test('John') obj.public() does anyone know how I can make this code work without getting rid of the exec statement?

18th Sep 2017, 4:35 PM
Daan van IJcken
Daan van IJcken - avatar
1 Answer
+ 7
Dunderscore methods won't work in exec as they are implicitly inaccessible. Prefix this method with a single underscore for it to work properly or change your designation of this method. It is not like a typical public/private/protected access known in other languages, but similar to some extent. Take a look at this thread at SO, it sums up the features of "private" methods in Python: https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-a-single-and-a-double-underscore-before-an-object-name
18th Sep 2017, 6:44 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar