我们使用的第三方库包含一个相当长的函数,它在其中使用嵌套函数.我们对该库的使用触发了该函数中的错误,我们非常希望解决该错误.
不幸的是,库维护者修复有点慢,但我们不想分叉库.在修复问题之前,我们也无法保留我们的版本.
我们更喜欢使用猴子修补来修复此问题,因为这比修补源更容易跟踪.然而,要重复一个非常大的功能,只需更换内部功能就足够了,并且让其他人更难看到我们究竟改变了什么.我们是否坚持使用图库蛋的静态补丁?
内部函数依赖于关闭变量; 一个人为的例子是:
def outerfunction(*args):
def innerfunction(val):
return someformat.format(val)
someformat = 'Foo: {}'
for arg in args:
yield innerfunction(arg)
Run Code Online (Sandbox Code Playgroud)
在哪里我们想要只替换它的实现innerfunction()
.实际的外部功能远远更长.当然,我们会重用关闭的变量并维护函数签名.
我有这些课程:
class Family(object):
__slot__ = ['father', 'var1']
def __init__(self, father, var1 = 1):
self.father, self.var1 = father var1
class Father(object):
__slots__ = ['var2']
def __init__(self, var2 = ''):
self.var2 = var2
father = Father()
family = Family(father = father)
Run Code Online (Sandbox Code Playgroud)
我想腌制"家庭"对象.所以我需要覆盖__getstate__
和__setstate__
"家庭"和"父亲"类.
你能告诉我一个有效的方法吗?(我使用的原因__slots__
是因为我有很多对象而且我正在努力节省内存)
我试图子类化json.JSONEncoder
这样的命名元组(使用新的Python 3.6+语法定义,但它可能仍适用于输出collections.namedtuple
)被序列化为JSON对象,其中元组字段对应于对象键.
例如:
from typing import NamedTuple
class MyModel(NamedTuple):
foo:int
bar:str = "Hello, World!"
a = MyModel(123) # Expected JSON: {"foo": 123, "bar": "Hello, World!"}
b = MyModel(456, "xyzzy") # Expected JSON: {"foo": 456, "bar": "xyzzy"}
Run Code Online (Sandbox Code Playgroud)
我的理解是我子类化json.JSONEncoder
并覆盖它的default
方法来为新类型提供序列化.然后,课程的其余部分将就递归等方面做正确的事情.因此我想出了以下内容:
class MyJSONEncoder(json.JSONEncoder):
def default(self, o):
to_encode = None
if isinstance(o, tuple) and hasattr(o, "_asdict"):
# Dictionary representation of a named tuple
to_encode = o._asdict()
if isinstance(o, datetime):
# String representation of a datetime
to_encode = …
Run Code Online (Sandbox Code Playgroud) 我在Windows上使用python 2.7.3.我试图将__instancecheck__
魔术方法覆盖为类方法.但我不能让它发挥作用.
class Enumeration(int):
@classmethod
def __instancecheck__(cls, inst):
if type(inst) == cls:
return True
if isinstance(inst, int) and inst in range(0,10):
return True
return False
print isinstance(1, Enumeration) # prints False
print isinstance(1, Enumeration()) # prints True
Run Code Online (Sandbox Code Playgroud)
我假设第一个print语句将为True.但似乎__instancecheck__
没有调用神奇的方法.我不知道为什么第二个print语句可以工作,因为isinstance
应该将class/type作为第二个参数.
有谁知道问题是什么?谢谢.
我已经尝试在Python 2.6中执行此操作,它确实"有效":
>>> def f(i='I'): return i
...
>>> f.func_defaults = (10,)
>>> f()
10
Run Code Online (Sandbox Code Playgroud)
但这是官方指定的行为,还是我遇到了特定于实现的行为?
我已经设置了一些我自己的类,这些类是从字典中继承的,就像它们一样.然而,当我想将它们编码为JSON(使用Python)时,我希望它们能够以一种我可以将它们解码回原始对象而不是dict的方式进行序列化.
所以我想支持我自己的类的嵌套对象(从dict继承).
我尝过这样的东西:
class ShadingInfoEncoder(json.JSONEncoder):
def encode(self, o):
if type(o).__name__ == "NodeInfo":
return '{"_NodeInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
elif type(o).__name__ == "ShapeInfo":
return '{"_ShapeInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
elif type(o).__name__ == "ShaderInfo":
return '{"_ShaderInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
return super(ShadingInfoEncoder, self).encode(o)
Run Code Online (Sandbox Code Playgroud)
和:
class ShadingInfoEncoder(json.JSONEncoder):
def encode(self, o):
if isinstance(o, NodeInfo):
return '{"_NodeInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
elif isinstance(o, ShapeInfo):
return '{"_ShapeInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
elif isinstance(o, ShaderInfo): …
Run Code Online (Sandbox Code Playgroud) python ×6
json ×2
closures ×1
encoding ×1
namedtuple ×1
nested ×1
python-3.6 ×1
recursion ×1
subclass ×1