-3

任何人都可以帮助解决这个问题:我需要在调用类之间保存的公共属性。有机会吗?请举例说明。

谢谢!

更新:如果打开两个终端,是否有能力在类之间共享值?

4

3 回答 3

6

是的,将其直接分配给您的班级:

class Foo(object):
    bar = None  # shared

    def __init__(self):
        type(self).bar = 'baz'  # still shared, *per subclass*
        Foo.bar = 'baz'         # still shared, across all subclasses*

类上的任何属性都在实例之间共享,除非您为实例分配相同的属性名称(这会掩盖类属性)。您可以通过直接分配给类属性来更改该值,方法是通过type(self)或直接引用类名。通过使用type(self)子类可以随时引用自己的类。

于 2013-06-21T22:12:16.257 回答
3

你的意思是,一个变量?像这样:

class Test(object):
    class_variable = None # class variable, shared between all instances
    def __init__(self):
        self.instance_variable = None # instance variable, one for each instance

例如:

a = Test()
b = Test()
Test.class_variable = 10
a.instance_variable = 20
b.instance_variable = 30

a.instance_variable
=> 20 # different values
b.instance_variable
=> 30 # different values

a.class_variable
=> 10 # same value
b.class_variable
=> 10 # same value
于 2013-06-21T22:12:35.650 回答
2

我刚刚回答了这样一个问题。小心做这个类变量的事情。这是可能的,但你不会得到你所期望的。

>>> class Foo():
...     LABELS = ('One','Two','Three')
... 
>>> Foo.LABELS
('One', 'Two', 'Three')
>>> Foo.LABELS = (1,2,3)
>>> Foo.LABELS
(1, 2, 3)
>>> f = Foo()
>>> g = Foo()
>>> f.LABELS = ('a','b','c')
>>> g.LABELS
(1, 2, 3)
>>> Foo.LABELS
(1, 2, 3)
>>> f.LABELS
('a', 'b', 'c')
于 2013-06-21T22:39:26.263 回答