Reputation: 162
If I create a class like below:
class Foo(object):
foo = {'useful_info': 'useful_info'}
def __init__(self, foo, bar):
self.foo['foo'] = foo
self.bar = bar
and I create an instances of it and print it's attributes as:
Foo1 = Foo('foo1', 'bar1')
print(Foo1.foo)
print(Foo1.bar)
I get the output:
Foo1 = Foo('foo1', 'bar1')
print(Foo1.foo)
print(Foo1.bar)
However, now if I create a new instance named Foo2 and print the attributes of both Foo1 and Foo2 as:
Foo2 = Foo('foo2', 'bar2')
print("Foo2.foo: ", Foo2.foo)
print("Foo2.bar: ", Foo2.bar)
print("Foo1.foo: ", Foo1.foo)
print("Foo1.bar: ", Foo1.bar)
I get the output:
Foo2.foo: {'foo': 'foo2'}
Foo2.bar: bar2
Foo1.foo: {'foo': 'foo2'}
Foo1.bar: bar1
The string attributes bar
have been set as I expect, but the dictionary foo
has been updated for both instances of Foo.
I can get round this by declaring the dict foo
in the init magic method as:
class Foo(object):
def __init__(self, foo, bar):
self.foo = {'useful_info': 'useful_info'}
self.foo['foo'] = foo
self.bar = bar
but now the dictionary foo
containing 'useful_info' isn't accessible until the init function is called i.e. if I use the line: Foo.foo
I get an AttributeError.
Is there any way to create a new dictionary containing some 'useful_infomation' so that the useful info is accessible before the class is initialised and every new instance of a class has a different instance of this dictionary.
Upvotes: 0
Views: 48
Reputation: 118011
You can make a copy.deepcopy
of the dictionary within __init__
so each instance has a deep copy of the dictionary, instead of sharing the same foo
dictionary object.
import copy
class Foo(object):
foo = {'useful_info': 'useful_info'}
def __init__(self, bar):
self.foo = copy.deepcopy(Foo.foo)
self.bar = bar
Upvotes: 1
Reputation: 96286
Just combine both:
class Foo:
foo = {'useful_info': 'useful_info'}
def __init__(self, foo, bar):
self.foo = {'useful_info': 'useful_info'}
self.foo['foo'] = foo
self.bar = bar
Upvotes: 1