August Williams
August Williams

Reputation: 929

Cannot access class variable to print as it is NoneType object

I have a class such as:

class MP3:
    name = ""
    capacity = 0
    def newMP3(name, capacity):
        MP3.name = name
        MP3.capacity = capacity

My main script:

from mp3class import *
currentMP3 = MP3.newMP3("myName", 10)
print (currentMP3.name)
print (currentMP3.capacity)

However, the print statements return an error:

AttributeError: 'NoneType' object has no attribute 'name'

Why is currentMP3 == None when I've just assigned it?

I've tried return (name, capacity) at the end of class MP3 and that gives me a different error:

AttributeError: 'tuple' object has no attribute 'name'

Even though the tuple does have name in it?

Upvotes: 0

Views: 1082

Answers (2)

Blckknght
Blckknght

Reputation: 104702

Your newMP3 method in your class doesn't return anything. In Python, that's the same as returning None. So when you do currentMP3 = MP3.newMP3(...), currentMP3 becomes None and doesn't have access to the class attributes you set on the MP3 class.

Note that your use of class attributes and no instances is a very odd one. I'd expect lots of other bugs if you keep going that route. A much more natural implementation would create an instance of the MP3 class and set attributes on the instance.

Upvotes: 0

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160377

You're returning None implicitly after calling:

def newMP3(name, capacity):
    MP3.name = name
    MP3.capacity = capacity

and assigning it to the name currentMP3.

You're either looking for __init__ to initialize a new instance with some attributes:

def __init__(self, name, capacity):
    self.name = name
    self.capacity = capacity

or, as an alternative, you can change the class attributes directly and then create a new instance with @classmethod:

@classmethod
def newMP3(cls, name, capacity):
    cls.name = name
    cls.capacity = capacity
    return cls()

Upvotes: 3

Related Questions