Search code examples
python-3.xclasscircular-dependency

Circular referencing between methods of classes in Python


My code has two classes that depend on each other in the following way.

class Shepherd:

    def __init__(self, name='Bob', address='Shepherd Way 1', sheep=[]):
        self.name=name
        self.address=address
        self.sheep=sheep # a list of objects of the class Sheep

class Sheep:

    def __init__(self, shepherd=Shepherd(), address=None, color='brown'):
        self.color=color
        # a sheep inherits the shepherd's address
        self.address=shepherd.address
        # and it gets added to the shepherd's list of sheep
        shepherd.sheep = shepherd.sheep + [self]

    def set_color(self, color='white'):
        self.color=color

I would now like to add a method set_sheep_color() to the Shepherd class. This method should use the method set_color on every sheep that a shepherd has. The problem is that I cannot do that because set_color get defined after the Shepherd class. However, I cannot move the definition of the Sheep class before the Shepherd class because I am using Shepherd() in the Sheep class. How can I add the set_sheep_color() to the Shepherd class after definition? Or is there a better way to solve this problem?


Solution

  • class Shepherd:
      ...
      def set_sheep_color(self, color):
        for s in self.sheep:
            s.set_color(color)
    

    The names that are attached to an object aren't checked until the line of code is actually executed. It doesn't matter if you're defining this before you've defined the Sheep class; it only matters whether you're running it before running the Sheep class. Which you've clearly already done, since you've initialized the Shepherd with some number of sheep that must already exist.

    In other words, when python looks at the variables and methods attached to an object, it looks at the object as it currently exists - not at the object's specification.