考虑以下代码:
import functools
import inspect
class Foo:
def foo_fn(self, hello, world):
print(hello, world)
class FooWrapper:
def __init__(self, foo_class):
self._foo = foo_class()
for key, value in inspect.getmembers(self._foo):
if inspect.ismethod(value):
bound_fn = functools.partial(self.foo_wrapper_fn, self, value)
setattr(self._foo, key, bound_fn)
def foo_wrapper_fn(self_wrapper, self_foo, bound_method, hello, world):
bound_method(hello, world)
def make_foo(Foo):
wrapper = FooWrapper(Foo)
return wrapper._foo
a = make_foo(Foo)
a.foo_fn("hello", "world")
Run Code Online (Sandbox Code Playgroud)
foo_wrapper_fn()像这样的功能参数如何排序(self_wrapper, self_foo, bound_method, hello, world)?而不是这样:self_wrapper, bound_fn, self_foo, hello, world,由于self_wrapper和bound_fn首先被部分绑定?
对象()调用返回functool.partial (而不是functool.partialmethod)可以 …
我正在研究零度规则,并且对最终的一段代码有两个问题,这些代码证明了规则.
class module {
public:
explicit module(std::wstring const& name)
: handle { ::LoadLibrary(name.c_str()), &::FreeLibrary } {}
// other module related functions go here
private:
using module_handle = std::unique_ptr<void, decltype(&::FreeLibrary)>;
module_handle handle;
};
Run Code Online (Sandbox Code Playgroud)
考虑下面的代码。逗号分隔时,Python如何解释类RottenFruit?这合法吗?如果是,用例是什么?
from enum import Enum
class Fruit(Enum):
Apple = 4
Orange = 5
Pear = 6
a = Fruit(5)
class RottenFruit(Enum):
Apple = 4,
Orange = 5,
Pear = 6
print(Fruit(5))
print(RottenFruit(5))
Run Code Online (Sandbox Code Playgroud)
输出:
Fruit.Orange
Traceback (most recent call last):
File "...\tests\sandbox.py", line 15, in <module>
print(RottenFruit(5))
File "...\AppData\Local\Programs\Python\Python36\lib\enum.py", line 291, in __call__
return cls.__new__(cls, value)
File "...\AppData\Local\Programs\Python\Python36\lib\enum.py", line 533, in __new__
return cls._missing_(value)
File "...\AppData\Local\Programs\Python\Python36\lib\enum.py", line 546, in _missing_
raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: …Run Code Online (Sandbox Code Playgroud)