Does Python have class prototypes (or forward declarations)?

前端 未结 6 1750
不思量自难忘°
不思量自难忘° 2020-11-28 10:06

I have a series of Python classes in a file. Some classes reference others.

My code is something like this:

class A():
    pass

class B():
    c = C         


        
6条回答
  •  迷失自我
    2020-11-28 10:21

    A decade after the question is asked, I have encountered the same problem. While people suggest that the referencing should be done inside the init method, there are times when you need to access the data as a "class attribute" before the class is actually instantiated. For that reason, I have come up with a simple solution using a descriptor.

    class A():
        pass
    
    class B():
        class D(object):
            def __init__(self):
                self.c = None
            def __get__(self, instance, owner):
                if not self.c:
                    self.c = C()
                return self.c
        c = D()
    
    class C():
        pass
    
    >>> B.c
    >>> <__main__.C object at 0x10cc385f8>
    

提交回复
热议问题