gpt4 book ai didi

python - 创建对象时 Class() vs self.__class__()?

转载 作者:太空狗 更新时间:2023-10-29 17:07:20 24 4
gpt4 key购买 nike

使用 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)

最佳答案

如果您从子类实例调用该方法,

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

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

关于python - 创建对象时 Class() vs self.__class__()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20623925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com