2011-04-22 86 views
4

使用這種例如由http://docs.python.org/tutorial/classes.html#class-objects在實例化類之前,在Python類中定義的方法的正確名稱是什麼?

class MyClass: 
    """A simple example class""" 
    i = 12345 
    def f(self): 
     return 'hello world' 

根據這些文檔,f是一個屬性引用返回一個功能對象。

有什麼簡短的方式說f是什麼?我可以稱它爲一個類的方法(注意我沒有說「類方法」,這是不正確的)?或者是一個類中定義的函數?或者一個實例方法?

換句話說,就與MyClass的關係而言,f的正式短期術語是什麼?

回答

6

如果你具體指通過MyClass.f返回f,然後f是MyClass的一個不受約束的方法。或者至少這是什麼REPL稱之爲:

>>> MyClass.f 
<unbound method MyClass.f> 

總的來說,雖然,我不認爲任何人會指責你簡單地稱它是「法」,簡單明瞭。或者,就其與MyClass的關係而言,MyClass的一種方法。

+1

或者可能是「MyClass方法」 - 無論如何,人們總是說「字符串方法」或「列表方法」。 – senderle 2011-04-22 04:27:58

4

我想說這是一個實例方法(或成員函數),因爲只有當您使用實例instance.f()MyClass.f(instance)綁定它時才能訪問此方法。

-1
x = MyClass() 
def __init__(self): 
    self.data = [] 
print x.i 
print x.f() 
print MyClass.__doc__ 

# Instance x = MyClass() 
# More __init__(self) is important 
# Sorry my english. I'm from Brazl 
+0

您不必定義'__init__'。原始問題中的類定義就足夠了。 – hpaulj 2013-08-19 07:15:04

相關問題