0

I don't believe in calling the magic functions or properties directly from outside of the class because they are private to the class and it's not the caller's responsibility to know about them but I can't find the equivalent public functions/properties.

If I have a class:

class A:
  def __init__(self):
    pass

def B:
  def __init__(self):
    pass

my_classes = {'one':A(), 'two':B()}

As an instance, how do I call the

my_val = some_func(input)
instance_type = my_classes[my_val]
instance_type.__name__ 
InfoLearner
  • 14,952
  • 20
  • 76
  • 124
  • I have a number of classes and I have a function that gets the right class and I want to pass the name of the chosen class as a parameter to a function. – InfoLearner Jun 10 '21 at 09:22
  • It's not a function ok. But it's a private property by naming convention. – InfoLearner Jun 10 '21 at 09:22
  • 1
    Using `__name__` is the correct way to get the name of a class, see https://stackoverflow.com/questions/510972/getting-the-class-name-of-an-instance – mkrieger1 Jun 10 '21 at 09:24

1 Answers1

1

I think you are confusing private functions/attributes with functions/attributes with double underscores before AND after the name. There is nothing wrong with accessing attributes with double underscores before and after the attribute. They are just labelled like that to avoid collisions, but it's legitimate to use, though something like __getattr__() probably doesn't make much sense to call outside of the class. But __name__ and __class__ are both okay to access.

I believe what you are thinking of is prefixing a function or attribute with double underscore. This will mangle the name and is not meant to be used/called outside the class. The difference is that they don't have a double underscore suffix.

class T():
   def __priv(self):
      pass

   def __special__(self):
      pass

   __attr = None

print(dir(T()))

You should see _T__priv, _T__attr, and __special__. So the double underscore before AND after will not mangle. I'm not sure making your own __someattribute__ is the best idea, but the builtin ones for sure are available to you to use.

saquintes
  • 1,074
  • 3
  • 11