Python Instantiate Class Within Class Definition

前端 未结 4 1000
小蘑菇
小蘑菇 2021-01-14 14:14

I am attempting to add a variable to a class that holds instances to the class. The following is a shortened version of my code.

class Classy :
    def __in         


        
4条回答
  •  长情又很酷
    2021-01-14 15:01

    The class itself is not defined until after the class block finishes executing, so you can't make use of the class inside its own definition.

    You could use a class decorator or a metaclass to add your desired class variable after the class is created. Here's an example with a decorator.

    def addClassy(cls):
        cls.CLASSIES = [cls() for a in xrange(4)]
        return cls
    
    @addClassy
    class Classy(object):
        pass
    
    >>> Classy.CLASSIES
    0: [<__main__.Classy object at 0x000000000289A240>,
     <__main__.Classy object at 0x000000000289A518>,
     <__main__.Classy object at 0x000000000289A198>,
     <__main__.Classy object at 0x000000000289A208>]
    

提交回复
热议问题