Python 创建对象时,类()与自身?

Python 创建对象时,类()与自身?,python,Python,使用Class()或self.\u Class\u()在类中创建新对象的优点/缺点是什么? 一种方法通常比另一种更可取吗 这是我所说的一个人为的例子 class Foo(object): def __init__(self, a): self.a =

使用Class()或self.\u Class\u()在类中创建新对象的优点/缺点是什么? 一种方法通常比另一种更可取吗

这是我所说的一个人为的例子

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)                                             

self.\uuuuu class\uuuuu
将使用子类的类型,如果您从子类实例调用该方法

显式使用该类将使用您显式指定的任何类(自然)

e、 g:


当然,这个例子除了说明我的观点外,是毫无用处的。在这里使用classmethod会更好。

Ah。这很有道理,回答得很好!太快了,+1。顺便说一句,帽子不错@哎呀,我觉得帽子是圣诞节我最喜欢的东西之一。不过有点好笑。。。在现实生活中,我从来都不难决定穿什么衣服——叠满帽子完全是另一回事…@mgilson LOL。它甚至适合各种图案!Haha@mgilson我认为,这是因为
self
引用了
Bar
对象。这就是为什么
self.\uuu class\uu
指向
Bar
对象。
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