课堂上的自我要求论证
由于某种原因,大多数类实例都返回类型错误,指出传递的参数不足,问题出在 self 上。 这工作得很好:
class ExampleClass:
def __init__(self, some_message):
self.message = some_message
print ("New ExampleClass instance created, with message:")
print (self.message)
ex = ExampleClass("message")
但是,我定义和调用实例的几乎所有其他类都会返回相同的错误。几乎相同的函数:
class Test(object):
def __init__(self):
self.defaultmsg = "message"
def say(self):
print(self.defaultmsg)
test = Test
test.say()
返回类型错误,表示它需要一个参数。我不仅在该类中遇到这个问题,而且在我定义的几乎每个类中都遇到这个问题,而且我不知道问题是什么。我刚刚更新了 python,但之前遇到了错误。我对编程相当陌生。
For some reason most instances of classes are returning Type errors saying that insufficient arguments were passed, the problem is with self.
This works fine:
class ExampleClass:
def __init__(self, some_message):
self.message = some_message
print ("New ExampleClass instance created, with message:")
print (self.message)
ex = ExampleClass("message")
However almost every other Class I define and call an instance of returns the same error. The almost identical function:
class Test(object):
def __init__(self):
self.defaultmsg = "message"
def say(self):
print(self.defaultmsg)
test = Test
test.say()
Returns a Type Error, saying that it needs an argument. I'm getting this problem not just with that class, but with pretty much every class I define, and I have no idea what the problem is. I just updated python, but was getting the error before. I'm fairly new to programming.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须实例化该类:
如果
您好奇,您可以尝试以下操作:
它有效,因为我将类实例(自身)赋予了未绑定方法!
绝对不建议以这种方式编码。
You have to instantiate the class:
instead of
if you are curious you can try this:
It works because I gave the class instance (self) to the unbound method !
Absolutely not recommended to code this way.
您应该添加括号来实例化一个类:
You should add parentheses to instantiate a class:
您的测试引用类本身,而不是该类的实例。要创建实际的测试实例或“实例化”它,请添加括号。例如:
错误消息试图告诉您没有这样的
self
对象可以(隐式)作为函数参数传递,因为在您的情况下test.say
将是一个未绑定的方法。Your test refers to the class itself, rather than an instance of that class. To create an actual test instance, or to 'instantiate' it, add the parentheses. For example:
The error message was trying to tell you that there was no such
self
object to pass in (implicitly) as the function argument, because in your casetest.say
would be an unbound method.