开发者

In python. class variable is static..is I want to use different instance. is there any solution?

开发者 https://www.devze.com 2023-02-15 00:03 出处:网络
In python, I want to make a cl开发者_C百科ass variable static so I can to use it from a different instance. is there any solution?I don\'t follow your question exactly, but it seems to me you\'re aski

In python, I want to make a cl开发者_C百科ass variable static so I can to use it from a different instance. is there any solution?


I don't follow your question exactly, but it seems to me you're asking how to make instance variables in Python. The answer is to set them inside a method, preferably __init__() using the self reference.

class Foo(object):
    classVar = 0 #this is a class variable. It is shared between all instances
    def __init__(self, instanceVar):
        self.someVar = instanceVar

obj1 = Foo(10)
obj2 = Foo(42)

print obj1.classVar # prints 0
print obj2.classVar # prints 0

print obj1.someVar #prints 10
print obj2.someVar #prints 42
0

精彩评论

暂无评论...
验证码 换一张
取 消