python - Why cant I access a property of an instance from another class? -


i've have trouble issue while now, , following example of problem:

class player(object):     def __init__(self):         self.weapon = "rifle"         self.rifle_test = rifle(self)         self.dictionary = {}         self.dictionary["rifle"] = self.rifle_test      def check(self):         print(self.weapon)         print(self.dictionary[self.weapon].ammo)  class rifle(object):     def __init__(self, player):         self.ammo = 10         self.player = player         self.player.check()  player_test = player() 

i have player ("player_test") , rifle ("rifle_test"). when call check() inside rifle(), nothing printed in console. i've tried moving things around, separating 2 classes , not having rifle_test in player_test, etc. main problem this: when execute function of specific instance instance, function executed not treated if executed instance carries it. in other words, if execute check() rifle(), different if execute player_test. there way execute function same way if execute player_test? thanks.

you have mutually-exclusive dependencies. closely @ happens when execute program:

first, create new player

player_test = player() 

creating new player means calling __init__ method on class, ...

class player(object):     def __init__(self:         self.weapon = "rifle"         self.rifle_test = rifle(self) 

oh! halfway through, create new rifle.

class rifle(object):     def __init__(self, player):         self.ammo = 10         self.player = player         self.player.check() 

alright, our rifle's created, , call self.player.check():

def check(self):     print(self.weapon)     print(self.dictionary[self.weapon].ammo) 

but wait! never finished creating player in first place. @ point, although self.weapon defined, self.dictionary has not yet been created.

the definition of check have depends on there being initialized self.dictionary, self.dictionary have depends on there being defined self.rifle_test, in turn depends on check.

this circular dependency, , it's not going work; need redesign. recommend removing call check() rifle's __init__.


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -