2013-02-22 41 views
0

所以我寫了一個修改電視節目標題的python腳本。這比練習更重要。我試圖使用@property裝飾器,但我的誤解是,當你做「var.property」時,我認爲var會傳遞給屬性...所以我試圖得到splitName()能夠使用基類中的hasDots屬性,但我不確定如何將名稱Var傳遞給屬性。我知道我可以用一種方法做到這一點,但我試圖學習如何使用屬性。一旦我可以讓基類正常工作,splitName()方法將成爲主要的方法。如何將值傳遞給python中的@property?

任何幫助,將不勝感激。我對python也很陌生,所以如果我正在做的任何「unpythonic」讓我知道。

exceptibleExts = ['.avi','.mkv','mp4'] 

class Base(object): 

    def __init__(self, source): 
     self.source = source 
     self.isTvShow() 


    # this method will return the file name 
    def fileName(self): 
     for name in self.source: 
      name, ext = os.path.splitext(name) 
      yield name, ext 


    @property 
    def isTvShow(self): 
     names = self.fileName() 
     for name in names: 
      if str(name[1]) in exceptibleExts and str(name[1]).startswith('.') == False: 
       return True 
      else: 
       return False 

    @property 
    def hasDots(self): 
     names = self.fileName() 
     for name in names: 
      if '.' in str(name[0]): 
       return True 
      else: 
       return False 


    @property 
    def hasDashes(self): 
     names = self.fileName() 
     for name in names: 
      if '-' in str(name[0]): 
       return True 
      else: 
       return False 

    @property 
    def startswithNumber(self): 
     names = self.fileName() 
     for name in names: 
      if str(name[0].lstrip()[0].isdigit()): 
       return True 
      else: 
       return False 

    @property 
    def hasUnderscore(self): 
     names = self.fileName() 
     for name in names: 
      if '_' in str(name[0]): 
       return True 
      else: 
       return False 

class names(Base): 
    def __init__(self, source): 
     self.source = source 
     #pass 

     self.splitName() 

    #this method returns true if the show title is in the file name... if not it will return false 
    def hasShowTitle(self): 
     pass 



    def splitName(self): 
     #names = self.fileNames 
     showInfo = {} 
     for name in self.fileName(): 
      print name.hasDots 
+0

什麼是「你正在試圖做」?代碼沒有做到你想要做的事情? – BrenBarn 2013-02-22 07:00:56

+0

我試圖讓splitName()能夠使用來自基類的hasDots屬性,但我不知道如何將名稱Var傳遞給屬性。我知道我可以用一種方法做到這一點,但我試圖學習如何使用屬性。 – 2013-02-22 07:02:37

+1

在開始時嘗試以程序風格編寫代碼。現在你的代碼很醜,很難理解你想要做什麼。例如「for self.fileName()中的名稱」的名稱是字符串,它沒有hasDots方法,並且使用camelCase不是phythonic。讓我們嘗試從基礎開始。 – Denis 2013-02-22 07:19:02

回答

2

當你正在學習某些東西時,仔細閱讀文檔是個好主意。

再看第三代碼示例這裏http://docs.python.org/3/library/functions.html#property

class C: 
    def __init__(self): 
     self._x = None 

    @property 
    def x(self): 
     """I'm the 'x' property.""" 
     return self._x 

    @x.setter 
    def x(self, value): 
     self._x = value 

    @x.deleter 
    def x(self): 
     del self._x 

你這是怎麼定義的屬性setter和刪除器定義使用內置的property裝飾。

P.S:對應的Python 2文檔是在這裏:http://docs.python.org/2/library/functions.html#property

+0

感謝您的回覆。這是非常有用的......我已經根據你的建議改變了我的編碼結構。 – 2013-02-28 03:40:11