0

So I added the id attribute to my class and I get this error:

File "C:\Users\Home pc\PycharmProjects\proiect final\domain\music.py", line 49, in eq if self._id == other.id: AttributeError: 'Music' object has no attribute 'id'

I am working in python 3.8

And this is my class

class Music:

    def __init__(self, title, artist, genre, duration, id):
        self._title = title
        self._artist = artist
        self._genre = genre
        self._duration = duration
        self._id = id

    def get_title(self):
        return self._title

    def get_artist(self):
        return self._artist

    def get_genre(self):
        return self._genre

    def get_duration(self):
        return self._duration

    def get_id(self):
        return self._id

    def set_title(self, title):
        self._title = title

    def set_artist(self, artist):
        self._artist = artist

    def set_genre(self, genre):
        self._genre = genre

    def set_duration(self, duration):
        self._duration = duration

    def set_id(self, id):
        self._id = id

    def __repr__(self):
         return "Title: {0}, Artist: {1}, Genre: {2}, Duration: {3} , Id: {4}".format(self._title, self._artist, self._genre,
                                                                               self._duration, self._id)

    def __str__(self):
        return "Title: {0}, Artist: {1}, Genre: {2}, Duration: {3}, Id: {4}".format(self._title, self._artist, self._genre,
                                                                               self._duration, self._id)

    def __eq__(self, other):
        if self._id == other.id:
            return True
        else:
            return False
Youness Saadna
  • 792
  • 2
  • 8
  • 25

1 Answers1

1

In your method to check for equality __eq__, you're checking for other.id instead of other._id. idis not a property of your class Music, as we see in __init__.

You have created methods for your class Music to access their attributes, yet in __eq__ you're directly accessing them. This issue could be solved by writing:

def __eq__(self, other):
    if self.get_id()== other.get_id():
        return True
    else:
        return False

And your __eq__ method could be further simplified:

def __eq__(self, other):
    return self.get_id()== other.get_id()
R. dV
  • 416
  • 1
  • 3
  • 15
  • There's no problem accessing private attributes directly from within the class though. – Ted Klein Bergman Aug 15 '20 at 10:06
  • I agree with you, Ted, but since he made the methods, it's also perfectly fine to use them within the class. It would also have saved him this problem – R. dV Aug 16 '20 at 11:08