G
G
gd1xza2021-10-30 13:20:17
Python
gd1xza, 2021-10-30 13:20:17

Python can't find private class method via eval?

note:

class a:
   def a(self):
       print(self.__b) # bound method a.__b
       eval('print(self.__b)') #  a object has no attribute __b

  def __b(self):
         pass

why and how to fix

Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class a:
...   def a(self):
...     print(self.__b)
...     eval('print(self.__b)')
...   def __b(self):
...     pass
...
>>> e = a()
>>> e
<__main__.a object at 0x000001CBE3F7C0C8>
>>> e.a()
<bound method a.__b of <__main__.a object at 0x000001CBE3F7C0C8>>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in a
  File "<string>", line 1, in <module>
AttributeError: 'a' object has no attribute '__b'
>>>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-10-30
@gd1xza

https://docs.python.org/3/tutorial/classes.html#pr...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question