当我尝试覆盖魔术方法__eq__,并使用super访问找到的基本方法时object,我收到一个错误.这不是一个错误,但它确实感觉像一个:
class A(object):
def __eq__(self, other):
return super(A, self).__eq__(other)
A() == 0
# raises AttributeError: 'super' object has no attribute '__eq__'
Run Code Online (Sandbox Code Playgroud)
这是不直观的,因为object.__eq__存在,但class A(object): pass它没有.如果我没有错误__eq__地进行is检查,那么这可能是解决方法,但使用is而super不是mixin友好.在我的情况下,这条路线是可以的,但在其他情况下可能不是.
任何建议,或关于为什么这样__eq__工作的信息都会很棒.
我知道这可能是一个重复的问题,但我无法找到解决方案。
简而言之,我有一个要解码的字符串:
raw = "\x94my quote\x94"
string = decode(raw)
Run Code Online (Sandbox Code Playgroud)
预期从字符串
'"my quote"'
Run Code Online (Sandbox Code Playgroud)
最后一点要注意的是,我正在使用 Python 3,因此rawunicode 也是如此,因此已经被解码。鉴于此,我究竟需要做什么来“解码”"\x94"字符?
考虑以下向函数parent和添加类型提示的尝试child:
def parent(*, a: Type1, b: Type2):
...
def child(*, c: Type3, d: Type4, **kwargs):
parent(**kwargs)
...
Run Code Online (Sandbox Code Playgroud)
MyPy抱怨说,kwargs有型Dict[str, Any],但该参数a和b要求Type1,并Type2分别。
我了解解决此错误的方法是child按以下方式重写:
def child(*, a: Type1, b: Type2, c: Type3, d: Type4, **kwargs):
parent(a=a, b=b)
...
Run Code Online (Sandbox Code Playgroud)
但是如果参数列表parent是多长,或有功能grandchild有其自身的参数列表和必须调用child。您是否需要从所有下游函数中枚举参数及其类型?或者是否有一种优雅的方式来处理**kwargs?
pip给定一些版本说明符,如何使用(或任何其他工具)安装依赖项的最低版本。因此,如果我要指定requests >=2.0, <3.0我实际上想要安装requests==2.0.
创建 Python 包时,您可能希望让用户能够在各种环境中与其交互。这意味着您经常会声称支持给定依赖项的多个版本。例如,人们可能会声称他们的软件包支持requests>=2.0. 这里的问题是,为了负责任地提出这一声明,我们需要某种方式来测试我们的包是否适用requests==2.0于最新版本以及介于两者之间的任何版本。
不幸的是,我不认为有一个很好的解决方案来测试一个人对所有可能的依赖项组合的支持,但您至少可以尝试测试您的依赖项的最大和最小版本。
为了解决这个问题,我通常会创建一个requirements.min.txt包含所有依赖项的最低版本的文件,这样当我想测试我的更改没有破坏我对旧版本的支持时,我可以安装它们。因此,如果我声称支持requests>=2.0我的requirements.min.txt文件,那么requests==2.0.
不过,这种针对一个人的最小依赖集进行测试的问题的解决方案感觉很混乱。有没有人也找到了一个好的解决方案?
在Python中工作,如何通过实例化的类检索元类(metamethod)所拥有的方法?在以下场景中,它很简单 - 只需使用getattr或点符号:
*所有示例都使用版本安全 with_metaclass
class A(type):
class A(type):
"""a metaclass"""
def method(cls):
m = "this is a metamethod of '%s'"
print(m % cls.__name__)
class B(with_metaclass(A, object)):
"""a class"""
pass
B.method()
# prints: "this is a metamethod of 'B'"
Run Code Online (Sandbox Code Playgroud)
然而,这是奇特的,因为'method'在任何地方都找不到dir(B).由于这个事实,重写这样的方法动态变得困难,因为元类不在查找链中super:
class A(type):
"""a metaclass"""
def method(cls):
m = "this is a metamethod of '%s'"
print(m % cls.__name__)
class B(with_metaclass(A, object)):
"""a class"""
@classmethod
def method(cls):
super(B, cls).method()
B.method()
# raises: "AttributeError: 'super' …Run Code Online (Sandbox Code Playgroud) python ×4
metaclass ×1
mypy ×1
pip ×1
python-2.7 ×1
python-3.5 ×1
python-3.x ×1
super ×1
type-hinting ×1
unicode ×1