Morteza Farhang
Morteza Farhang

Reputation: 85

Passing a class as argument to a function and use it's methods

Quite simple, I wanna pass a class to a function as argument, while the class that I'm using has several methods. Here's the class: (parent is also a Node)

class Node:
    def __init__(self,parent,foods):
        self.state = state
        self.foods = foods
        self.parent = parent

    def getParent(self):
        return self.parent

    def getFoods(self):
        return self.foods

And somewhere else in a function I'm passing this class to function, but seems that I can't use all attributes. Here's the function:

def CalculateSomethingAboutThisNode(node):
     daddy = node.getParent()
     foodsOfDaddy = daddy.getFoods()

But I'm getting this error:

line 551, in CalculateSomethingAboutThisNode
   foodsOfDaddy = daddy.getFoods()
AttributeError: 'NoneType' object has no attribute 'getFoods'

Please hep me out here.

Upvotes: 0

Views: 146

Answers (2)

Leonid Blouvshtein
Leonid Blouvshtein

Reputation: 41

you should correct your code:

def CalculateSomethingAboutThisNode(node):
 if not node is None:
  daddy = node.getParent()
  foodsOfDaddy = daddy.getFoods()

Upvotes: 1

Simeon Visser
Simeon Visser

Reputation: 122326

The node has no parent. In other words: it's a root node.

As such it can happen that daddy is None and that means daddy.getFoods() won't work.

Upvotes: 3

Related Questions