2013-01-08 8 views
7
class Foo(): 
    def __init__(self): 
     pass 
    def create_another(self): 
     return Foo() 
     # is not working as intended, because it will make y below becomes Foo 

class Bar(Foo): 
    pass 

x = Bar() 
y = x.create_another() 

y powinien być klasy Bar nie Foo.Konstruktor wywołania Python z własnej instancji

Czy jest coś takiego: self.constructor() używać zamiast tego?

Odpowiedz

24

Dla klas w nowym stylu, użyj type(self) dostać „aktualny” Klasa:

def create_another(self): 
    return type(self)() 

Można także użyć self.__class__ jako że jest to wartość type() użyje, ale stosując metodę API jest zawsze zalecane.

Dla klas w starym stylu (Python 2, nie dziedziczy z object) type() nie jest tak pomocne, więc jesteś zmuszony do korzystania self.__class__:

def create_another(self): 
    return self.__class__() 
+2

@Billiska: Chyba, że ​​masz dobry powód, aby to zrobić Używałbym jednak klas w nowym stylu. Niech 'Foo' dziedziczy z' obiektu'. –

Powiązane problemy