无法在Python中调用类内的函数

2024-04-19 15:35:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学Python。当我试图调用类中的函数时,出现了这个错误。所以请帮我解决这个问题。你知道吗

tony@kali:~$ python
Python 2.7.13 (default, Jan 19 2017, 14:48:08) 
[GCC 6.3.0 20170118] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class H:
...            def y():
...                  print "j"
... 
>>> g=H
>>> g.y()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method y() must be called with H instance as first argument (got nothing instead)
>>> H.y()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method y() must be called with H instance as first argument (got nothing instead)
>>> 

Tags: inmoststdinlinebecallmethodfile
2条回答

您必须初始化class,然后只有您可以调用该class的方法。而且,方法的第一个参数应该是self。你知道吗

class H:
   def y(self):
         print "j"
g = H()
g.y()

有关self的更多详细信息,请参阅here。你知道吗

你绝对应该检查this chapter类。你知道吗

你有答案和评论,让我解释一下错误信息。你知道吗

在代码中,gH是同一事物的不同名称,因此这两个错误是一个。你知道吗

现在,H是一个(旧式)类,它下面的所有函数def都是方法,除非用classmethodstaticmethod之类的技巧“处理”。当您作为H的属性访问这些方法时,它们被称为“未绑定”方法,因为它们尚未绑定到类H实例。你知道吗

为了理解Python的类、方法和属性的核心模型,我推荐Shalabh Chaturvedi的优秀文章:

<>太长了,读不下去了:通常你会调用一个实例,调用一个实例的绑定EME>方法:

>>> class H(...):
>>>     def y(...):
>>> h_instance = H()
>>> h_instance.y(...)

Python将把这个实例(h_instance放在伪代码段中)作为方法的第一个参数。如果将其称为h_instance.y(),则实际参数列表为(h_instance);如果将其称为h_instance.y(a),则参数为(h_instance, a)。你知道吗

这就是为什么您几乎总是发现方法定义中的第一个形式参数是self。这个名称没有什么特别之处,只是Python希望为调用该方法的实例保留这个槽。它允许您用一个空参数列表定义方法,但是当您实际使用实例时,这个列表就没有用了。在这种情况下,您将始终得到TypeError,因为调用发送一个参数(“self”实例),而方法定义中没有参数。你知道吗

作为演示,请考虑以下会议:

In [1]: class H(object):    # New-style class, doesn't matter here.
   ...:     def y(self):    # Notice the call signature: "self" included
   ...:         print "j"        

In [2]: h_instance = H()    # Create an instance from the class

# This is how normally you're expected to call. There's no argument
# passed to the *bound* to the instance h_instance, because when you do
# this Python will carry out the syntactic desugaring and call on the
# instance.
In [3]: h_instance.y()
j

# This does the same thing and demonstrates the concept of an
# unbound method.  It's not bound to any specific instance of H, so
# you'll have to specify which instance to call.
In [4]: H.y(h_instance)
j

相关问题 更多 >