我有一个返回函数的包装函数.有没有办法以编程方式设置返回函数的docstring?如果我可以写信,__doc__我会做以下事情:
def wrapper(a):
def add_something(b):
return a + b
add_something.__doc__ = 'Adds ' + str(a) + ' to `b`'
return add_something
Run Code Online (Sandbox Code Playgroud)
然后我就能做到
>>> add_three = wrapper(3)
>>> add_three.__doc__
'Adds 3 to `b`
Run Code Online (Sandbox Code Playgroud)
但是,由于__doc__是只读的,我不能这样做.什么是正确的方法?
编辑:好的,我想保持这个简单,但当然这不是我真正想要做的.虽然一般来说__doc__在我的情况下是可写的但事实并非如此.
我正在尝试unittest自动创建测试用例.我有一个包装函数,它创建一个类对象,它是以下的子类unittest.TestCase:
import unittest
def makeTestCase(filename, my_func):
class ATest(unittest.TestCase):
def testSomething(self):
# Running test in here with data in filename and function my_func
data = loadmat(filename)
result = my_func(data)
self.assertTrue(result > 0)
return ATest
Run Code Online (Sandbox Code Playgroud)
如果我创建这个类并尝试设置docstring testSomething我得到一个错误: …
在 Python 中,我可以使用@classmethod装饰器创建一个类方法:
>>> class C:
... @classmethod
... def f(cls):
... print(f'f called with cls={cls}')
...
>>> C.f()
f called with cls=<class '__main__.C'>
Run Code Online (Sandbox Code Playgroud)
或者,我可以在元类上使用普通(实例)方法:
>>> class M(type):
... def f(cls):
... print(f'f called with cls={cls}')
...
>>> class C(metaclass=M):
... pass
...
>>> C.f()
f called with cls=<class '__main__.C'>
Run Code Online (Sandbox Code Playgroud)
如 的输出所示C.f(),这两种方法提供了相似的功能。
@classmethod在元类上使用和使用普通方法有什么区别?
我试图覆盖__str__和__repr__类,如下面的代码所示。每当我调用 instance_method 时都会调用新方法,但对 class_method 的对象调用保持不变(请参阅下面的代码片段和输出,以便于了解)。有没有办法可以覆盖__str__and __repr__for@classmethod以便cls可以更改的值?
我也尝试添加__str__和__repr__as@classmethod但没有任何改变。
class Abc:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Added {self.name}"
def __repr__(self):
return f"instance method repr"
def instance_method(self):
print(f"instance method {self}")
@classmethod
def __repr__(cls):
return f"class method"
@classmethod
def __str__(cls):
return f"class method"
@classmethod
def class_method(cls):
print(f"class method '{cls}'")
@staticmethod
def static_method():
print(f"static method")
def add(self, a: int,b: int,c: int) -> int:
return …Run Code Online (Sandbox Code Playgroud)