Using object as a class

Paul Moore p.f.moore at gmail.com
Mon Mar 26 09:24:12 EDT 2018


In fact, object acts just like a user-defined class, with __slots__
set to empty:

>>> class MyObj(object):
...     __slots__ = ()
...
>>> o = MyObj()
>>> o.x = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyObj' object has no attribute 'x'

See https://docs.python.org/3.6/reference/datamodel.html#slots

IIRC, most built in objects (of which object is one) behave as if they
have __slots__ set (they don't actually, because they are written in
C, but the effect is the same).

Paul

On 26 March 2018 at 13:31, D'Arcy Cain <darcy at vybenetworks.com> wrote:
> It's called a super class but it doesn't quite work like a normal class.
>
>>>> OBJ = object()
>>>> OBJ.x = 3
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'object' object has no attribute 'x'
>
> I can fix this by creating a NULL class.
>
>>>> class NullObject(object): pass
> ...
>>>> OBJ = NullObject()
>>>> OBJ.x = 3
>>>> OBJ.x
> 3
>>>>
>
> Is this behaviour (object not quite like a class) documented anywhere?
> Does anyone know the rationale for this if any?
>
> In case anyone wants to know why I am doing this, sometimes I simply
> want an object to hold values that I can pass around.  I don't need
> methods and I don't always know what variables I am going to need.
>
> And yes, I know that dict is the usual way to do this.
>
> --
> D'Arcy J.M. Cain
> Vybe Networks Inc.
> http://www.VybeNetworks.com/
> IM:darcy at Vex.Net VoIP: sip:darcy at VybeNetworks.com
> --
> https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list