2013-12-17 61 views
11

使用Class()或self.__ class __()在類中創建新對象有什麼優點/缺點? 一種方法通常比另一種更受歡迎嗎?創建對象時,Class()vs self .__ class __()

下面是我正在談論的一個人爲的例子。

class Foo(object):                
    def __init__(self, a):               
    self.a = a                 

    def __add__(self, other):              
    return Foo(self.a + other.a)             

    def __str__(self):                
    return str(self.a)               

    def add1(self, b):                
    return self + Foo(b)               

    def add2(self, b):                
    return self + self.__class__(b)            

回答

10

self.__class__,如果你從一個子類的實例調用該方法將使用一個子類的類型。

使用類明確將使用什麼類,你明確指定(自然)

例如爲:

class Foo(object): 
    def create_new(self): 
     return self.__class__() 

    def create_new2(self): 
     return Foo() 

class Bar(Foo): 
    pass 

b = Bar() 
c = b.create_new() 
print type(c) # We got an instance of Bar 
d = b.create_new2() 
print type(d) # we got an instance of Foo 

當然,這個例子是相當無用除了演示我的觀點。在這裏使用classmethod會好得多。

+0

啊。這就說得通了。 – Ben

+0

很棒的回答!也快,+1。順便說一句,好帽子! – aIKid

+1

@aIKid - 我認爲StackOverflow帽子是我最喜歡的聖誕節時間之一。這很有趣,雖然...我從來沒有很難決定在現實生活中穿什麼衣服 - Stack Overflow帽子完全是另一回事... – mgilson