Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance of class `object`

Tags:

python

I wish to make an instance of built-in class object, and use it as container for some variables (like struct in C++):

Python 3.2 (r32:88445, Mar 25 2011, 19:56:22) 
>>> a=object()
>>> a.f=2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'f'

Is there a way to accomplish this easier than doing:

>>> class struct():
...     '''Container'''
... 
>>> a=struct()
>>> a.f=2
>>> a.f
2
>>> 

UPDATE:

  • i need a container to hold some variables, but i don't want to use dict - to be able to write a.f = 2 instead of a['f'] = 2

  • using a derived class saves you from typing the quotes

  • also, sometimes autocomplete works

like image 411
warvariuc Avatar asked Feb 07 '26 00:02

warvariuc


2 Answers

I recognize the sentiment against dicts, and I therefore often use either NamedTuples or classes. Nice short hand is provided by Bunch in the Python Cookbook, allowing you to do declaration and assignment in one:

point = Bunch(x=x, y=y, squared=y*y)
point.x

The printed Cookbook (2ed) has an extensive discussion on this.

IMHO, the reason why object has no slots and no dict is readability: If you use an (anonymous) object to store coordinates first and then another object to store client data, you may get confused. Two class definitions makes it clear which one is which. Bunches don't.

like image 142
dirkjot Avatar answered Feb 08 '26 13:02

dirkjot


No, you have to subclass object to get a mutable object. Make sure to do so explicitly in python 2.x:

class Struct(object):
    pass

Probably using a built-in container is better though, if only because it's clear from syntax exactly what it is.

The reason instances of object can't be assigned to is that they don't have either a __dict__ or a __slots__ attribute, the two places where instance data can be stored.

>>> dir(object())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', 
 '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', 
 '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Basically this is equivalent to declaring __slots__ = [].

If you know all the fields you want your Struct to have, you could use slots to make a mutable namedtuple-like data structure:

>>> class Foo(object):
...     __slots__ = ['a', 'b', 'c']
... 
>>> f = Foo()
>>> f.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: a
>>> f.a = 5
>>> f.a
5

But you can only assign values to attribute names listed in __slots__:

>>> f.d = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'd'
like image 35
senderle Avatar answered Feb 08 '26 14:02

senderle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!