Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #70532 > unrolled thread
| Started by | Cameron Simpson <cs@zip.com.au> |
|---|---|
| First post | 2014-04-23 16:11 +1000 |
| Last post | 2014-04-23 16:11 +1000 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: object().__dict__ Cameron Simpson <cs@zip.com.au> - 2014-04-23 16:11 +1000
| From | Cameron Simpson <cs@zip.com.au> |
|---|---|
| Date | 2014-04-23 16:11 +1000 |
| Subject | Re: object().__dict__ |
| Message-ID | <mailman.9454.1398233498.18130.python-list@python.org> |
On 23Apr2014 09:39, Pavel Volkov <sailor@lists.xtsubasa.org> wrote: >There are some basics about Python objects I don't understand. >Consider this snippet: > >>>>class X: pass >... >>>>x = X() >>>>dir(x) >['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', >'__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', >'__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', >'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', >'__sizeof__', '__str__', '__subclasshook__', '__weakref__'] >>>>x.foo = 11 > >And now I want to make a simple object in a shorter way, without >declaring X class: > >>>>y = object() >>>>dir(y) >['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', >'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', >'__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', >'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', >'__subclasshook__'] >>>>y.foo = 12 >Traceback (most recent call last): > File "<stdin>", line 1, in <module> >AttributeError: 'object' object has no attribute 'foo' > >The attribute list is different now and there's no __dict__ and the >object does not accept new attributes. >Please explain what's going on. The base "object" class has a fixed set of attributes; you can't add more. Almost every other class lets you add attributes, but the price for that is that it is slightly in memory footprint and slower to access. Look up the "__slots__" dunder var in the Python doco index: https://docs.python.org/3/glossary.html#term-slots You'll see it as a (rarely used, mostly discouraged) way to force a fixed set of attributes onto a class. As with object, this brings a smaller memory footprint and faster attribute access, but the price is flexibility. Cheers, Cameron Simpson <cs@zip.com.au> Try being nothing but bored for 4 hours straight, and then tell me that there's no fear involved. - dave@elxr.jpl.nasa.gov (Dave Hayes)
Back to top | Article view | comp.lang.python
csiph-web