1

So python is dynamic. I should be able to add attributes to class instances willy-nilly.

I'm trying to do this:

spam = None
spam.eggs = []

But apparently I can't add an attribute to None.

How do I define spam as an instance of an undefined 'empty class' to which I can add attributes as I go along?

4

3 に答える 3

7
class Bag(object):
  pass

spam = Bag()
spam.eggs = []
于 2013-02-08T16:30:54.160 に答える
3

いいえ、許可されているオブジェクト タイプに属性を追加できます。Noneobject、 、typeなどint。アル。それらは不変であるため、しないでください。

于 2013-02-08T16:33:03.700 に答える
2

In Python 3.3+ using types.SimpleNamespace:

from types import SimpleNamespace

spam = SimpleNamespace(eggs=[])
print(spam) # -> namespace(eggs=[])
spam.rice = {}
print(spam) # -> namespace(eggs=[], rice={})
于 2013-02-08T17:02:18.560 に答える