Reputation: 125
i'd like to return a new instance of the current class, when an inherited class return it will return the base class instead of the current class
class class1:
def __init__(self):
self.foo = 1
self.bar = 2
def new(self):
return class1()
class class2(class1):
def __init__(self):
super().__init__()
c1 = class1()
c2 = class2()
print(c1.new())
print(c2.new())
this returns
<main.class1 object at 0x0000027B681E57F0>
<main.class1 object at 0x0000027B681E57F0>
desired result
<main.class1 object at 0x0000027B681E57F0>
<main.class2 object at 0x0000027B681E57F0>
Upvotes: 1
Views: 4953
Reputation: 12208
you can get the current class like this:
class class1:
def __init__(self):
self.foo = 1
self.bar = 2
def new(self):
return self.__class__()
Inheritors will return their own classes. You will have to handle the logic for any different __init__
signatures yourself, however. A classmethod would be a better design choice unless you needed information from the current instance to create the new one.
Upvotes: 1
Reputation: 500317
You could use __class__
for that:
class class1(object):
def new(self):
return self.__class__()
class class2(class1):
pass
c1 = class1()
c2 = class2()
print(c1.new())
print(c2.new())
Upvotes: 4
Reputation: 531075
Define a class method instead:
class Class1:
def __init__(self):
self.foo = 1
self.foo = 2
@classmethod
def new(cls):
return cls()
class Class2(Class1):
pass
Now when you call c2.new()
, the runtime will see that Class2
has no method named new
, but Class1
does. Further, Class2
will be passed as the implicit argument to new
, not Class1
.
The class method is more appropriate than an instance method because you don't have any other interest in the object invoking the method beyond what class it is.
Upvotes: 3