2016-07-29 24 views
1

A部分蟒蛇__new__ - 如何在不繼承

實現我想要做的一些參數來檢查一個類的實例,並可能返回None,如果它沒有意義,甚至創建對象。

我已閱讀文檔,但我不明白在這種情況下返回

class MyClass: 
    def __new__(cls, Param): 
     if Param == 5: 
      return None 
     else: 
      # What should 'X' be? 
      return X 

我應該Xreturn X

  • 它不可能是self因爲對象不存在,卻又如此self是不是在這方面有效的關鍵字。

B部分

綁在我的問題,我不明白需要cls參數。

如果您打電話給MyClass的構造函數 - var = MyClass(1) - 是不是cls總是MyClass
它怎麼可能是其他的東西?

根據該文檔,clsobject.__new__(cls[, ...])是:

. . .the class of which an instance was requested as its first argument.

+0

你最有可能比返回'None'更適合拋出異常。 – DeepSpace

+0

@DeepSpace注意。但在某些情況下返回「無」可能是有意義的。 – Adrian

+0

沒關係,只要你記得那個。 – DeepSpace

回答

0

(我假設,因爲你提供的鏈接到Python 3個文檔您正在使用Python 3)

X可能是super().__new__(cls)

super()返回父類(在這種情況下,它只是object)。大多數情況下,當你重寫方法時,你需要在某個時候調用父類的方法。

見這個例子:

class MyClass: 
    def __new__(cls, param): 
     if param == 5: 
      return None 
     else: 
      return super().__new__(cls) 

    def __init__(self, param): 
     self.param = param 

然後:

a = MyClass(1) 

print(a) 
print(a.param) 

>> <__main__.MyClass object at 0x00000000038964A8> 
1 

b = MyClass(5) 

print(b) 
print(b.param) 

>> None 
    Traceback (most recent call last): 
    File "main.py", line 37, in <module> 
    print(b.param) 
    AttributeError: 'NoneType' object has no attribute 'param' 
+0

'super()'返回什麼? – Adrian

+0

我讀過[超級文檔](https://docs.python.org/3/library/functions.html#super),但我毫無疑問困惑。 – Adrian

+0

@Adrian'super()'返回父類,在本例中爲'object'。我認爲你正在使用Python 3,是否正確? – DeepSpace

0

你可以只返回這樣return object.__ new__(cls) CLS的實例。因爲每個類都是object的子類,所以可以將其用作類的對象創建者。回傳對象作爲第一個參數傳遞給__init__(),並傳遞給任何數量的位置參數或任何數量的關鍵字參數。在那裏您將創建分配這些值的實例變量。

+0

如何返回'cls'的實例? [這是'__init__'被調用的必要條件。](https://docs.python.org/3/reference/datamodel.html#object.__new__) – Adrian

+0

這個問題就像python如何創建對象一樣。對於每個objcet創建,在調用__init __(),__ new __()之前。參考這個頁面,這可能會給你一個清晰的想法。 http://eli.thegreenplace.net/2012/04/16/python-object-creation-sequence –

+0

「......一個實例被請求作爲它的第一個參數的類。」這意味着班級的名字。如果你打印'cls',它將打印它爲'__main __。MyClassName' –