Python Forum

Full Version: anonymous method in a class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a class named foo with a method named bar. i want to create another method named woot that can be referenced by bar but not as an attribute of foo. do i name it _woot?
Yes, a leading underscore is a common way to indicate that a method doesn't belong to the classes public interface.
i know that import won't import those for modules. does that work the same way for methods of classes?
No, they are ordinary methods, only client developer knows that he shouldn't be using this method.
basically i was asking if there was a way to hide the methods like i hide functions (and variables) in a module. i'll try defining functions inside a method. this is a class with only one method (beyond init) so putting them there won't be an issue.
Again the question is why do you want to do that? Why do you need to hide methods more than with an underscore to tell the world that this is not a public method?
for things (i don't create) that gather up object attribute names and do stuff i don't want done. but i can live with this. i just wanted to know if there was a way.
Skaperen Wrote:i just wanted to know if there was a way.

Methods are just functions after all. A simple way to hide private methods is to define them completely outside the class.
>>> class A:
...     def spam(self):
...         x = hidden(self)
...         return f'{self}: {x}'
... 
>>> def hidden(self):
...     return id(self)
... 
>>> a = A()
>>> a.spam()
'<__main__.A object at 0x7f697e056100>: 140091062575360'
it will be visible in the module, so i need to name it _hidden. yeah, i can put it outside the class. then every method, when i have one than one, can use it.