2016-08-04 4 views
1

Вот мой код:питона - Не похоже, чтобы вызвать метод родительского класса от ребенка

from mutagen.easyid3 import EasyID3 
from mutagen import File 

class MusicFile: 
    """A class representing a particular music file. 

    Children that are intended to be instantiated must initialize fields for 
    the getters that exist in this class. 
    """ 

    def __init__(self, location): 
     self.location = location 

    def getLocation(): 
     return self.location 

    def getArtist(): 
     return self.artist 

    def getAlbum(): 
     return self.album 

    def getTitle(): 
     return self.title 

############################################################################### 


class LossyMusicFile(MusicFile): 
    """A class representing a lossy music file. 

    Contains all functionality required by only lossy music files. To date, that 
    is processing bitrates into a standard number and returning format with 
    bitrate. 
    """ 
    def __init__(self, location): 
     super().__init__(location) 

    def parseBitrate(br): 
     """Takes a given precise bitrate value and rounds it to the closest 
     standard bitrate. 

     Standard bitrate varies by specific filetype and is to be set by the 
     child. 
     """ 
     prevDiff=999999999 
     for std in self.bitrates: 
      # As we iterate through the ordered list, difference should be 
      # getting smaller and smaller as we tend towards the best rounding 
      # value. When the difference gets bigger, we know the previous one 
      # was the closest. 
      diff = abs(br-std) 
      if diff>prevDiff: 
       return prev 
      prevDiff = diff 
      prev = std 

    def getFormat(): 
     """Return the format as a string. 

     look like the format name (a class variable in the children), followed 
     by a slash, followed by the bitrate in kbps (an instance variable in the 
     children). a 320kbps mp3 would be 'mp3/320'. 
     """ 
     return self.format + '/' + self.bitrate 


############################################################################### 

class Mp3File(LossyMusicFile): 
    """A class representing an mp3 file.""" 

    format = "mp3" 

    # Threw a large value on the end so parseBitrate() can iterate after the end 
    bitrates = (32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 
       128000, 160000, 192000, 224000, 256000, 320000, 999999) 

    def __init__(self, location): 
     super().__init__(location) 

     id3Info = EasyID3(location) 
     self.artist = id3Info['artist'][0] 
     self.album = id3Info['album'][0] 
     self.title = id3Info['title'][0] 
     # Once we set it here, bitrate shall be known in kbps 
     self.bitrate = (self.parseBitrate(File(location).info.bitrate))/1000 

Теперь, когда я пытаюсь создать экземпляр Mp3File, он дает мне ошибку на последнюю строку Mp3File.__init__():

line 113, in __init__ 
self.bitrate = (self.parseBitrate(File(location).info.bitrate))/1000 
NameError: name 'parseBitrate' is not defined 

Тем не менее, мне кажется, что это должно быть не в состоянии найти способ в Mp3File, а затем ищет метод в родительском классе, LossyMusicFile, где она существует.

Я попытался изменить эту строку на self.bitrate = (super().parseBitrate(File(location).info.bitrate))/1000 так, чтобы она явно использовала метод родительского класса, но я получаю ту же ошибку. Что происходит?

Извините, если это было задано раньше или является немым вопросом, но я не мог найти его, когда искал, и я, по сути, немой.

+4

Все ваши методы экземпляра ** должны ** иметь 'self' в качестве первого параметра. – James

+0

Смотрите мой обновленный ответ ... –

+0

С моим хрустальным шаром я могу позвонить, что вы используете Python 2 .... –

ответ

2

Все ваши методы экземпляра должны иметь значение self в качестве первого параметра. Что здесь происходит, так это то, что в parseBitrate() вы переименовали self в br. Вам нужно parseBitrate(self, br), чтобы принять битрейт. Вы должны добавить self в список аргументов другими способами, например getFormat().

  1. Ваш код использует thisVariableNamingStyle это против OFFICAL документа в стиле Пайтона, PEP 8.
  2. MusicFile не наследует от object. Вы можете вызывать только методы, унаследованные от более высокого класса в классах нового стиля. Чтобы сделать ваш класс «новым», вы должны наследовать object.

Кроме того, получите IDE, например PyCharm, который может автоматически предупредить вас об этих ошибках в будущем.

+2

Это Python 3.x, так что наследование от 'объекта' встроено. – Matthias

+0

Красивая, спасибо. Я не подбирал python через некоторое время после работы над проектом на Java. Кажется, я взял некоторые вредные привычки! – lucas755

+0

@ lucas755 PyCharm бесплатно, кстати –

Смежные вопросы