Pythonic Way to Initialize (Complex) Static Data Members

后端 未结 3 1995
闹比i
闹比i 2021-02-05 09:14

I have a class with a complex data member that I want to keep \"static\". I want to initialize it once, using a function. How Pythonic is something like this:

de         


        
3条回答
  •  轮回少年
    2021-02-05 09:31

    You're right on all counts. data_member will be created once, and will be available to all instances of coo. If any instance modifies it, that modification will be visible to all other instances.

    Here's an example that demonstrates all this, with its output shown at the end:

    def generate_data():
        print "Generating"
        return [1,2,3]
    
    class coo:
        data_member = generate_data()
        def modify(self):
            self.data_member.append(4)
    
        def display(self):
            print self.data_member
    
    x = coo()
    y = coo()
    y.modify()
    x.display()
    
    # Output:
    # Generating
    # [1, 2, 3, 4]
    

提交回复
热议问题