0

When I run this code, I get an error "AttributeError: 'NoneType' object has no attribute 'test'"

class BaseClass:
    def __new__(self, number):
        self.test = 1

class InheritedClass(BaseClass):
    pass

instance = InheritedClass(1)
print(instance.test)

Can someone explain to me what exactly gets inherited from the base? There seems to be a difference between Python 2 and 3, because if I put "test" in the attribute field of the Baseclass I can access it in Python 2, but not in 3.

timgeb
  • 76,762
  • 20
  • 123
  • 145
Kona98
  • 139
  • 2
  • 9
  • I don't think that this is discussed in the duplicate answer. The difference in behaviour between Python 2 and 3 is that `__new__()` exists only for new-style classes, i.e. those that are explicitly inherited from `object`. In your code `__new__()` is not even called in Python 2. In Python 3 it is called, but there is no instance because `__new__()` returns `None` - `__new__()` should return the instance. The answers in the duplicate address this latter point in more detail. – mhawke Dec 01 '17 at 10:56

2 Answers2

0

Try to replace "new" to "init"

class BaseClass:
    def __init__(self, number):
        self.test = 1

class InheritedClass(BaseClass):
    pass

instance = InheritedClass(1)
print(instance.test)
Kirill
  • 1
0

There is difference between new and init. To access fields like this you should call them in init.

MiBa
  • 1
  • 1