Python Instantiate Class Within Class Definition

前端 未结 4 985
小蘑菇
小蘑菇 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 14:52

    The simplest way to do this is do it after the class is created, when the class has been defined, and therefore can be used:

    class Classy :
        CLASSIES = []
    
        def __init__(self) :
            self.hi = "HI!"
    
    Classy.CLASSIES = [Classy() for _ in xrange(0,4)]
    

    (Here using a list comprehension for convinience, as it's the most readable and efficent way to build a list).

    Also note that if this intended to be a constant, you should probably make it a tuple rather than a list, and if it isn't intended to be, you should probably not use an ALL_CAPS name which, by convention, implies a constant.

提交回复
热议问题