Can't access attributes in python

1.3k Views Asked by At

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.

2

There are 2 best solutions below

1
On

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)
1
On

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