2017-08-02 26 views

回答

10

聽起來好像你想讓Card上的一元減法運算符返回一個新的卡片,其值爲否定。如果這是你想要的,你可以在你的類定義__neg__操作是這樣的:

class Card: 
    def __init__(self, val): 
     self.val = val 
    def __neg__(self): 
     return Card(-self.val) 

__neg__包括在方法列表,可以覆蓋到這裏定製的算術運算:https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types

+0

我怎樣才能知道所有預定義的函數,比如__neg__? –

+0

很有幫助:) –

+0

這在Python文檔中描述了用於模擬數字類型。你詢問的操作是「一元減號」。一元意義它作用於一個操作數。)https://docs.python.org/2.7/reference/datamodel.html#special-method-names –