创建对象时Class()vs self .__ class __()?

Ben*_*Ben 16 python

使用Class()或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)                                             
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 13

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
Run Code Online (Sandbox Code Playgroud)

当然,这个例子除了证明我的观点外毫无用处.在这里使用类方法会好得多.