0

How can I refer to the currently being defined class?

class A(object):
    # how can I use A here?

What I need to write is

class A(object):

    @some_decorator(A)
    @staticmethod
    def foo():
        pass

some_decorator registers an event listener that will trigger on some interaction with an A object. The A class itself needs to respond to these events in a way that interacts with private (__ mangled) data.

Cirdec
  • 24,019
  • 2
  • 50
  • 100
  • Could you give some context? What would some_decorator be doing? Perhaps a metaclass would be more appropriate. – jonrsharpe Aug 25 '17 at 17:20
  • Please add more context to your question. – Mike - SMT Aug 25 '17 at 17:20
  • You can't. This is a classic problem that has been discussed quite a bit (especially in the context of type annotations and checkers like mypy). What are you actually trying to accomplish? – mgilson Aug 25 '17 at 17:22
  • Interesting. @mgilson why would someone want to refer to a class from inside the class? Keep in mind I only know python. I have not began to learn other languages yet. – Mike - SMT Aug 25 '17 at 17:23
  • @SierraMountainTech the example of type annotations would be e.g. a method that returns an instance of the class, but you can't do `def foo() -> A:` as `A` isn't bound yet - see https://stackoverflow.com/q/15853469/3001761 – jonrsharpe Aug 25 '17 at 17:25
  • @jonrsharpe thanks for your example however after doing some reading I think this is a topic that I need to spend some time in as it is not something I am grasping easily. Would the method that returns an instance of the class need to be a method that is called from outside the class object? It does not seam like something that can be called during the `__init__` of the object creation and actually work. – Mike - SMT Aug 25 '17 at 17:41
  • @SierraMountainTech it doesn't matter. Could be a parameter instead of return value, with the method called from inside or outside of the class/instance. The type annotations are added *at class definition time*, before the class is created. And you *can* call instance, static and class methods from the same class's `__init__`. – jonrsharpe Aug 25 '17 at 18:44
  • @jonrsharpe well just goes to show the more I think I know about python the more I realize I have yet to learn. Time to spend another few days on a subject I am lacking in :D – Mike - SMT Aug 25 '17 at 18:45

0 Answers0