MyClass
及其实例在myModule.py
中定义:
class MyClass(object):
pass
obj = MyClass()
将function
定义为obj
的方法:
from myModule import obj
def function(msg):
print msg
如何使用MyClass
作为方法扩展function
个实例?
一种方式:
obj.function = function
但这与在类定义中定义的不一样,例如:
class MyClass(object):
def __init__(self):
self.value = 'Value'
def function(self, msg):
print msg, self.value
将function
定义为MyClass
方法后,它可以访问类的属性,例如self.value
。
答案 0 :(得分:1)
我不知道你为什么要重复这个问题,因为wim和I都提供了不涉及子类化的解决方案。
当在MyClass定义中定义function()时,它能够访问Class的一个或多个变量,例如self.value ....
我已经从你的另一篇文章中扩展了我的答案,以证明这已经成为现实:
from unittest import mock
# This class would be defined in some third-party library
class MyClass:
def __init__(self):
self._private_property = 'foo'
def method(self, msg):
print('from method:', msg)
def function(self, msg):
print('Accessing private property from function:', self._private_property)
print('from function:', msg)
old_method = MyClass.method
def new_method(self, msg):
old_method(self, msg)
function(self, msg)
# The patch is only applied within this scope
with mock.patch.object(MyClass, 'method', new_method):
foo = MyClass()
foo.method('message with patched')
# By this point MyClass is "back to normal"
print('---')
foo.method('message with original')
<强>输出强>
from method: message with patched
Accessing private property from function: foo
from function: message with patched
---
from method: message with original
答案 1 :(得分:0)
class MyClass(object):
def __init__(self):
self.value = 'value'
def function(self, msg):
print 'msg:', msg, 'value:', self.value
foo = MyClass()
foo.function = function.__get__(foo)
foo.function(msg = 'hello world')