[英]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
) 这是课程:(父级也是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. 请帮我在这里。
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. 因此,有可能daddy
是None
daddy.getFoods()
None
,这意味着daddy.getFoods()
无法工作。
you should correct your code: 您应该更正您的代码:
def CalculateSomethingAboutThisNode(node):
if not node is None:
daddy = node.getParent()
foodsOfDaddy = daddy.getFoods()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.