1
class Base:
    def __init__(self):
        self.x = 4

class C1(Base):
    ...

class C2(Base):
    ...

obj1 = C1()
obj2 = C2()

obj1.x = 2

I understand with "Singletons" if I change "self.x" of C1 it could automatically update "self.x" of every instance of that single class... but how would I update all classes using the same base?

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Wayne
  • 105
  • 1
  • 3

3 Answers3

1

Move the x declaration out of the init:

class Base:
    x = 4

    def __init__(self):

Later when you need to set it, do the following:

Base.x = 5

You could wrap this into a @staticmethod to make it easier as well.

As others have mentioned, static variables are really bad and you shouldn't use them unless it's your last resort.

Srdjan Grubor
  • 2,605
  • 15
  • 17
1

Someone correct me if i'm wrong but this can be solved easily with a reaaaal simple descriptor so for example:

class KeepSync(object):
    def __init__(self, default):
        self.value = default
    def __get__(self, instance, owner):
        return self.value
    def __set__(self, instance, value):
        self.value = value

class Foo(object):
    bar = KeepSync(0) 

class C1(Foo):
    pass

class C2(Foo):
    pass



f = C1()
g = C2()

print "f.bar is %s\ng.bar is %s" % (f.bar, g.bar)
print "Setting f.bar to 10"
f.bar = 10
print "f.bar is %s\ng.bar is %s" % (f.bar, g.bar)  # YAY BOTH ARE 10 !

Any object that inherits KeepSync descriptor will always return that value, i'm not sure if I helped but, that's how I understood the problem, you wouldn't even need a base class but you can

jozxyqk
  • 16,424
  • 12
  • 91
  • 180
Bojan Jovanovic
  • 1,439
  • 2
  • 19
  • 26
0

What you are trying to do won't work. While the initial x = 4 is stored on the class, not the instance, any assignment such as obj1.x = 2 will store it on the instance.

If you really want to create a singleton, (ab)use a metaclass to ensure that each instance created is actually the same one. See this answer for an example how to do it.

Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • The problem with this example is that it only updates all instances of the same class. it wouldn't update obj2 when I change "self.x" in obj1 – Wayne Oct 30 '13 at 14:07
  • This is the "singleton" that I was referring to in my original post. – Wayne Oct 30 '13 at 14:08
  • Oh, you want it to ignore inheritance. Should be easy to update the metaclass to use the base class as the key for the `_instances` dict instead of the actual class. – ThiefMaster Oct 30 '13 at 14:10