1

Say I have a custom class Box:

class Box(object):
    pass

I try to add an attribute prop:

box = Box()
box.prop = 1     # works
print(box.prop)  # 1

But if I do the same thing on an int object:

num = 1
num.prop = 1

Result

AttributeError: 'int' object has no attribute 'prop'

Questions:

  1. How to explain behavioural difference between num and box?
  2. How can I make a custom class (Box2) behave like an int, i.e. to raise AttributeError after box2 = Box2(); box2.prop = 1?
Frozen Flame
  • 3,135
  • 2
  • 23
  • 35
  • Check out `__slots__`. – g.d.d.c Oct 22 '14 at 07:22
  • 1
    When you type `num = 1`, `type(num)` is `int`, `int` doens't have `prop` attribute. You can use `__slots__` and have only wanted attributes in it. – Maroun Oct 22 '14 at 07:23
  • @MarounMaroun So doesn't `box` or `Box` have `prop` attribute. But why `box.prop = 1` is allowed? – Frozen Flame Oct 22 '14 at 07:28
  • For more info, see http://lucumr.pocoo.org/2014/8/16/the-python-i-would-like-to-see/ –  Oct 22 '14 at 07:28
  • 1
    @MichaelBrennan: slots he describes are not about `__slots__`. – jfs Oct 22 '14 at 07:32
  • related: [Python `__slots__`](http://stackoverflow.com/q/472000/4279) – jfs Oct 22 '14 at 07:33
  • @J.F.Sebastian You're right. I knew that, but got confused, again. –  Oct 22 '14 at 08:17
  • Here couple of links that'll help you https://docs.python.org/2/reference/datamodel.html#object.__setattr__ , https://docs.python.org/2/howto/descriptor.html . – pavel_form Oct 22 '14 at 10:26

0 Answers0