class one(object):
b=squares
def squares(self):
print('hi')
收到以下错误:
NameError:name' square'未定义
答案 0 :(得分:0)
这对你有用。让我解释一下。第一个代码应该放在方法里面,这些方法可以组合成类。您不应该直接在类中放置代码。
在Python实例化对象时,直接调用__init__(self)
方法。此方法采用self
参数,该参数将保存此类可用的属性和函数。在我们的例子中,我添加了一个名为self.size = 5
的属性。然后我们调用squares(self)
函数。请注意,我们将其作为self.function_name()
访问。
然后在该函数中我们传递self
参数。请注意我们如何从此函数访问self.size
属性。
class one(object):
def __init__(self):
self.size = 5
b = self.squares()
def squares(self):
print('hi' + str(self.size))
o = one()
如果您想要一个与您的对象无关的泛型函数。然后你需要在课前定义它。
def squares(a):
return a*a
class One():
def __init__(self, a):
self.num = a
self.example()
def example(self):
b=squares(self.num)
print(b)
obj = One(4)