2013-12-17 60 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