本文介绍了如何替换实例中的方法。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的程序中,我希望这个实例在调用inst.m1时最终调用repmeth

。就像现在一样,我收到这个错误:


来自init的Hello

inst =< __ main__.CC实例位于0x402105ec>

Traceback(最近一次调用最后一次):

文件" ./ foo9.py",第17行,在?

inst.m1()

TypeError:repmeth()只需1个参数(0给定)

#! / usr / bin / python

def repmeth(self):

print" repmeth"


class CC:

def __init __(自我):

self.m1 = repmeth

打印''来自初学者''


def m1(个体经营):

打印" m1"


inst = CC()

inst.m1 ()


TIA


-

时间过得很快。果蝇像香蕉一样苍蝇。奇怪的事情有.0。

发生但没有比这更奇怪。你的驾驶执照是否说器官..0

捐助者?黑洞是上帝除以零的地方。听我说!我们全都是个人b $ b!如果这不是一个假设的问题怎么办?

steveo在syslang.net

解决方案



删除self来自repmeth,因为它在函数中不是必需的,只在一个类中定义的

函数中。当然,

类中的函数也被认为是一种方法。


Mike





排序。如果你陈述你想要达到的目标,也许你会更好,

而不是你认为你应该怎么做。你可能不需要在__init__中替换一个方法,但是还有另一种不那么棘手的方法。


/ W

In the program below, I want this instance to end up calling repmeth
whenever inst.m1 is called. As it is now, I get this error:

Hello from init
inst = <__main__.CC instance at 0x402105ec>
Traceback (most recent call last):
File "./foo9.py", line 17, in ?
inst.m1()
TypeError: repmeth() takes exactly 1 argument (0 given)
#! /usr/bin/python
def repmeth( self ):
print "repmeth"

class CC:
def __init__( self ):
self.m1 = repmeth
print ''Hello from init''

def m1 ( self ):
print "m1"

inst = CC()
inst.m1()

TIA

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver''s license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren''t a hypothetical question?
steveo at syslang.net

解决方案

Remove "self" from repmeth as it''s not required in a function, only in
functions that are defined within a class. Of course, a function in a
class is also know as a method.

Mike



Sort of. Maybe you fare better if you state what you want to achieve,
instead of how you think you should do it. Chances are you don''t need to
replace a method in __init__, but there''s another, less tricky way.

/W


这篇关于如何替换实例中的方法。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 08:22