Why is this ok
class Ship:
def __init__(self, parent):
self.parent = parent
class Fleet:
def __init__(self):
self.ships = []
def add_ship(self, ship: Ship):
self.ships.append(ship)
But this is not?
class Fleet:
def __init__(self):
self.ships = []
def add_ship(self, ship: Ship):
self.ships.append(ship)
class Ship:
def __init__(self, parent):
self.parent = parent
I know that you cannot have circular references in importing. However, this is not an import thing: both of these are in the same file. In both cases the definition of Ship is made, but it seems as though if Fleet is defined first it can't find the definition of Ship. This is not true if I used isinstance
to check the type.
def add_ship(self, ship):
if isinstance(ship, Ship): # works fine
self.ships.append(ship)
However, that does not allow my IDE (PyCharm) to see the definition and autocomplete syntax.
In fact, the following design pattern seems to work fine
class Fleet:
def __init__(self):
self.ships = []
def add_ship(self, ship):
if isinstance(ship, Ship):
self.ships.append(ship)
class Ship:
def __init__(self, parent):
if isinstance(parent, Fleet):
self.parent = parent
But, again, does not allow for my IDE to figure out the types. This is Python 3.6.5/Anaconda/Windows 10.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…