python中self原理實例分析

字號:


    本文實例講述了python中self原理。分享給大家供大家參考。具體分析如下:
    類的方法與普通的函數(shù)只有一個特別的區(qū)別——它們必須有一個額外的第一個參數(shù)名稱,但是在調(diào)用這個方法的時候你不為這個參數(shù)賦值,Python會提供這個值。這個特別的變量指對象本身,按照慣例它的名稱是self。
    假如你有一個類稱為MyClass和這個類的一個實例MyObject。當(dāng)你調(diào)用這個對象的方法 MyObject.method(arg1, arg2) 的時候,這會由Python自動轉(zhuǎn)為 MyClass.method(MyObject, arg1, arg2)——這就是self的原理了。
    這也意味著如果你有一個不需要參數(shù)的方法,你還是得給這個方法定義一個self參數(shù)。
    示例程序:
    >>> class P:
    ... def selfDemo(self):
    ... print 'Python, why self?'
    ...
    ...
    >>> p = P()
    >>> p.selfDemo()
    Python, why self?
    >>>
    將selfDemo()中參數(shù)換為其他,如selfDemo(x),輸出同樣結(jié)果。
    若不加參數(shù),則報錯:
    >>> class P:
    ... def selfDemo(): # have no arguments
    ... print 'Python, why self?'
    ...
    ...
    >>> p = P()
    >>> p.selfDemo()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: selfDemo() takes no arguments (1 given)
    >>>
    希望本文所述對大家的Python程序設(shè)計有所幫助。