Can't set attributes on instance of “object” class

后端 未结 7 1354
囚心锁ツ
囚心锁ツ 2020-11-22 10:10

So, I was playing around with Python while answering this question, and I discovered that this is not valid:

o = object()
o.attr = \'hello\'
<
7条回答
  •  天命终不由人
    2020-11-22 10:33

    So, investigating my own question, I discovered this about the Python language: you can inherit from things like int, and you see the same behaviour:

    >>> class MyInt(int):
           pass
    
    >>> x = MyInt()
    >>> print x
    0
    >>> x.hello = 4
    >>> print x.hello
    4
    >>> x = x + 1
    >>> print x
    1
    >>> print x.hello
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: 'int' object has no attribute 'hello'
    

    I assume the error at the end is because the add function returns an int, so I'd have to override functions like __add__ and such in order to retain my custom attributes. But this all now makes sense to me (I think), when I think of "object" like "int".

提交回复
热议问题