首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python函数

python函数
EN

Stack Overflow用户
提问于 2012-01-12 16:44:55
回答 2查看 219关注 0票数 2
代码语言:javascript
复制
class Test:
       def func():
           print('func')
test1 = Test()
test2 = Test()

test1.func()  #TypeError: fun1() takes no arguments (1 given)
test2.newfunc = Test.func
test2.newfunc()#It goes well

# update part
def foo(self):
    pass
Test.foo = foo
test1.foo # it is bound method
test2.foo = foo
test2.foo # it is function
# end 

这两种方式有什么区别吗?谢谢。

代码语言:javascript
复制
# update part
def foo(self):
    pass
Test.foo = foo
test1.foo # it is bound method
test2.foo = foo
test2.foo # it is function
# end 

注意,重要的是检索应该在类中进行,而不是在实例中。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-12 17:46:44

稍微调查一下:

代码语言:javascript
复制
>>> test1.func
<bound method Test.func of <__main__.Test instance at 0x800f211b8>>
>>> Test.func
<unbound method Test.func>

然后调用用户定义的绑定方法(在我们的例子中是test1.func),这个调用实际上是作为Test.func(test1)类的实例作为第一个参数传递的。

有关此主题的更多信息,请参阅Python Data model

编辑

上面的输出来自Python 2.6。由于Test.func()适用于您,因此我假设您使用的是Python3。在这种情况下,输出将是下一个:

代码语言:javascript
复制
>>> test1.func
<bound method Test.func of <__main__.Test object at 0xb747624c>>
>>> Test.func
<function func at 0xb74719ec>

正如您所看到的,Test.func是一个简单的函数,因此在调用它时不会添加“魔法”。

票数 2
EN

Stack Overflow用户

发布于 2012-01-12 16:47:18

在类的实例上调用的类的方法会自动将实例引用作为参数传递。因此,它们通常使用self参数声明:

代码语言:javascript
复制
class Test:
       def func(self):
           print('func')

test1 = Test()
test1.func() # self = test1
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8832185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档