我在Objective-C中使用它我有这个结构:
- (void)init {
if (self = [super init]) {
// init class
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
Python是否也应该调用父类的实现__init__?
class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class
Run Code Online (Sandbox Code Playgroud)
对于__new__()和,这也是真/假__del__()吗?
编辑:有一个非常类似的问题:Python中的继承和覆盖__init__
我是Python修饰者的新手(哇,很棒的功能!),我无法让下面的代码工作,因为self参数混淆了.
#this is the decorator
class cacher(object):
def __init__(self, f):
self.f = f
self.cache = {}
def __call__(self, *args):
fname = self.f.__name__
if (fname not in self.cache):
self.cache[fname] = self.f(self,*args)
else:
print "using cache"
return self.cache[fname]
class Session(p.Session):
def __init__(self, user, passw):
self.pl = p.Session(user, passw)
@cacher
def get_something(self):
print "get_something called with self = %s "% self
return self.pl.get_something()
s = Session(u,p)
s.get_something()
Run Code Online (Sandbox Code Playgroud)
当我运行这个时,我得到:
get_something called with self = <__main__.cacher object at 0x020870F0>
Traceback:
...
AttributeError: 'cacher' …Run Code Online (Sandbox Code Playgroud) 当我们装饰功能时,我们使用functools.wraps使装饰功能看起来像原始.
当我们想要装饰类时,有没有wat做同样的事情?
def some_class_decorator(cls_to_decorate):
class Wrapper(cls_to_decorate):
"""Some Wrapper not important doc."""
pass
return Wrapper
@some_class_decorator
class MainClass:
"""MainClass important doc."""
pass
help(MainClass)
Run Code Online (Sandbox Code Playgroud)
输出:
class Wrapper(MainClass)
| Some Wrapper not important doc.
|
| Method resolution order:
| Wrapper
| MainClass
| builtins.object
|
# ... no MainClass important doc below.
Run Code Online (Sandbox Code Playgroud)
我尝试根据functools.wraps源代码编写类装饰器的包装,但我的实现不正确:
import functools
def wraps_cls(original_cls):
def wrapper(wrapper_cls):
"""Update wrapper_cls to look like original_cls."""
for attr in functools.WRAPPER_ASSIGNMENTS:
try:
value = getattr(original_cls, attr)
except AttributeError:
pass
else: …Run Code Online (Sandbox Code Playgroud) 我Functools.update_wrapper()在装饰器中使用,但似乎update_wrapper只重写函数属性(如__doc__,__name__),但不影响help()函数.
我知道这些答案,但它们不适用于装饰器类.
这是我的功能.
import functools
class memoized(object):
def __init__(self, func):
self.func = func
functools.update_wrapper(self, func)
def __call__(self, *args):
self.func(*args)
@memoized
def printer(arg):
"This is my function"
print arg
Run Code Online (Sandbox Code Playgroud)
这是输出
>>> printer.__doc__
This is my function
>>> help(printer)
Help on memoized in module __main__ object:
printer = class memoized(__builtin__.object)
| Methods defined here:
|
| __call__(self, *args)
|
| __init__(self, func)
|
| ----------------------------------------------------------------------
| Data descriptors defined here: …Run Code Online (Sandbox Code Playgroud) 我有一组不相关的类(一些是导入的),它们都有一个a类型为 的公共属性(或属性) dict[str, Any]。
其中akey 下应该有另一个字典"b",我想将其作为属性公开在任何这些类上b以简化inst.a.get("b", {})[some_key]为inst.b[some_key]。
我已将以下子类工厂用作本地类的类装饰器和导入类的函数。
但到目前为止,我未能cls正确键入提示其参数并返回值。
from functools import wraps
def access_b(cls):
@wraps(cls, updated=())
class Wrapper(cls):
@property
def b(self) -> dict[str, bool]:
return self.a.get("b", {})
return Wrapper
Run Code Online (Sandbox Code Playgroud)
我最近一次打字尝试的 MRE(有mypy 0.971错误):
from functools import wraps
from typing import Any, Protocol, TypeVar
class AProtocol(Protocol):
a: dict[str, Any]
class BProtocol(AProtocol, Protocol):
b: dict[str, bool]
T_a = TypeVar("T_a", bound=AProtocol)
T_b = TypeVar("T_b", bound=BProtocol)
def …Run Code Online (Sandbox Code Playgroud) 我有一个装饰器,它包装函数并生成类(出于比以下示例更好的原因)。这一切都有效,除了我希望能够设置type().
例如,
>>> class Animal:
... pass
...
>>> def linnean_name(genus, species):
... def _linnean_name(fn):
... class _Animal(Animal):
... binomial_name = (genus, species)
... def converse(self):
... fn()
... _Animal.__name__ = fn.__name__.title()
... _Animal.__module__ = fn.__module__
... return _Animal
... return _linnean_name
...
>>> @linnean_name('Vombatus', 'ursinus')
... def Wombat():
... print("Hello, I am a wombat.")
...
>>> sheila = Wombat()
>>> sheila.binomial_name
('Vombatus', 'ursinus')
>>> sheila.converse()
Hello, I am a wombat.
Run Code Online (Sandbox Code Playgroud)
一切都很好,但是
>>> type(sheila)
<class '__main__.linnean_name.<locals>._linnean_name.<locals>._Animal'>
Run Code Online (Sandbox Code Playgroud)
我希望看到的地方
<class …Run Code Online (Sandbox Code Playgroud)