2012-05-17 179 views
0

「字符串的方法」,如圖所示,例如:定義自定義字符串方法

teststring = "[Syllabus]Sociology.131.AC.Race.and.Ethnicity.in.the.United.States (Spring 2012).docx" 
print teststring.replace('.', ' ') 

「[大綱]社會學131 AC人種和種族中美國(2012年春季)DOCX」

是太棒了,我正在寫的腳本涉及很多文本操作,這是我正在做的很多事情,當我添加功能時,它仍然很重要。

一個常見的操作我做的是:

teststring = "[Syllabus]Sociology.131.AC.Race.and.Ethnicity.in.the.United.States (Spring 2012).docx" 
def f_type(f): return f.split('/')[-1] if os.path.isdir(f) else re.split(r'(\[Syllabus\]|\[Syllabus \d+\]|\[Video\]|)(.*?)(\(Fall \d+\)| \(Spring \d+\)| \(Summer \d+\)|)(\.part\d+\.rar$|\.\w+$)', f.split('/')[-1])[1] 
def f_name(f): return f.split('/')[-1] if os.path.isdir(f) else re.split(r'(\[Syllabus\]|\[Syllabus \d+\]|\[Video\]|)(.*?)(\(Fall \d+\)| \(Spring \d+\)| \(Summer \d+\)|)(\.part\d+\.rar$|\.\w+$)', f.split('/')[-1])[2] 
def f_term(f): return f.split('/')[-1] if os.path.isdir(f) else re.split(r'(\[Syllabus\]|\[Syllabus \d+\]|\[Video\]|)(.*?)(\(Fall \d+\)| \(Spring \d+\)| \(Summer \d+\)|)(\.part\d+\.rar$|\.\w+$)', f.split('/')[-1])[3] 
def f_ext(f): return f.split('/')[-1] if os.path.isdir(f) else re.split(r'(\[Syllabus\]|\[Syllabus \d+\]|\[Video\]|)(.*?)(\(Fall \d+\)| \(Spring \d+\)| \(Summer \d+\)|)(\.part\d+\.rar$|\.\w+$)', f.split('/')[-1])[4] 
print f_type(teststring) 
print f_name(teststring) 
print f_term(teststring) 
print f_ext(teststring) 

[大綱] Sociology.131.AC.Race.and.Ethnicity.in.the.United.States (2012年春季) .docx

但我希望能夠添加:「.ftype()」,「.fname()」,「.fterm()」和「.fext()」方法(對應於這些功能我)。我不知道該怎麼做。

我會在腳本中使用它在一堆不同的功能(所以它不會被類綁定或任何東西)。

我什至不知道我應該谷歌。但是我怎樣才能添加這些方法?

P.S.方法的名稱並不重要 - 所以如果我必須更改這些名稱以避免與內置方法衝突或沒有問題。

編輯:我希望能夠用這個方法對於像:

def testfunction(f1, f2): print 'y' if f1.ftype()==f2.ftype() else 'n' 

,所以我不希望它被綁定到一個字符串或做任何事情,我想成爲能夠將其用於不同的字符串。

回答

4

您不能將方法添加到像str這樣的內置類型。

但是,您可以創建str的子類並添加所需的方法。作爲獎勵,請添加@property,因此您無需調用該方法即可獲取該值。

class MyString(str): 
    @property 
    def f_type(f): 
     return f.split('/')[-1] if os.path.isdir(f) else re.split(r'(\[Syllabus\]|\[Syllabus \d+\]|\[Video\]|)(.*?)(\(Fall \d+\)| \(Spring \d+\)| \(Summer \d+\)|)(\.part\d+\.rar$|\.\w+$)', f.split('/')[-1])[1] 

s = MyString(teststring) 
s.f_type 

通常,你會用self作爲名稱中的方法的參數列表(即接收到的方法連接到該實例的引用的)第一個參數。在這種情況下,我只是使用f,因爲您的表達已被寫入使用它。

+0

但是,這不會讓我使用'如果a_ftype()== b_ftype():do_something' –

+0

當然,假設你的意思是'a.f_type == b.f_type'。 'a'和'b'只需要成爲你的'str'子類而不是普通的字符串,這很容易實現。 – kindall