Python Instantiate Class Within Class Definition

前端 未结 4 956
小蘑菇
小蘑菇 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:46

    The class body is executed before the class is created. Therefore, you are attempting the instantiate the class before it exists. You can still attach instances to the class, but you have to create them after the class body finished, e.g.:

    class Classy(object):
        def __init__(self):
            self.hi = "HI!"
        CLASSIES = []
    
    for i in xrange(4):
        Classy.CLASSIES.append(Classy())
    

    However, I'd suggest you first think long and hard whether you actually need this effectively-global list, and whether you need it to be part of the class object. Personally, I almost never do something like this.

提交回复
热议问题