Python 3.7引入了dataclasses
模块,其中包含一个@dataclass
装饰器。该装饰器可以生成类函数。如何打印这些生成的函数?
答案 0 :(得分:0)
我自己问了同样的问题。 Dataclasses
部分项目应具有详细选项,但没有。
发现此video很有帮助。根据视频数据,classes.py是代码生成器。因此,这应该是我们获得代码的第一个想法。
我尝试了以下代码:
from dataclasses import dataclass
import inspect
import os
from uncompyle6 import PYTHON_VERSION, deparse_code2str
@dataclass
class C:
name: str
value: int = 34
inspect.getmembers(C) #('__init__', <function __init__(self, name: str, value: int = 34) -> None>)
co= C.__init__.__code__ # let's find out code for the __init__ method from code object
code = deparse_code2str(
code=co,
version=PYTHON_VERSION,
out=open(os.devnull, "w"))
print(code)
将打印
self.name = name
self.value = value
该代码首先使用检查器理解类,然后使用Python反编译器反编译方法。
以下是发现的方法:
def __eq__(self, other):
if other.__class__ is self.__class__:
return (self.name, self.value) == (
other.name,
other.value,
)
else:
return NotImplemented
def __init__(self, name: str, value: int = 34) -> None:
self.name = name
self.value = value
def __repr__(self):
key = (id(self), _thread.get_ident())
if key in repr_running:
return "..."
else:
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
实际上有一个project正在执行@dataclass发现。我安装好了,就可以了。
from dataclasses import dataclass
import inspect
import os
import dis
from DataclassInspector.inspector import Inspector
@dataclass
class C:
name: str
value: int = 34
inspected = Inspector(C)
print(inspected._generate_code())
提供了这样的输出:
from dataclasses import Field, _MISSING_TYPE, _DataclassParams
class C:
__dataclass_fields__ = {'name': "Field(name='name', type=str, default=_MISSING_TYPE, default_factory=_MISSING_TYPE, init=True, repr=True, hash=None, compare=True, metadata={}, _field_type=_FIELD)", 'value': "Field(name='value', type=int, default=34, default_factory=_MISSING_TYPE, init=True, repr=True, hash=None, compare=True, metadata={}, _field_type=_FIELD)"}
__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)
name: str
value: int = 34
def __eq__(self, other):
if other.__class__ is self.__class__:
return (self.name, self.value) == (other.name, other.value)
else:
return NotImplemented
__hash__ = None
def __init__(self, name: str, value: int = 34) -> None:
self.name = name
self.value = value
def __repr__(self):
key = (
id(self), _thread.get_ident())
if key in repr_running:
return '...'
else:
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
答案 1 :(得分:0)
检查 dataclass implementation 后,这些方法似乎是由 dataclasses._create_fn
生成的。为了获得原始生成的代码,我将函数模拟为:
import dataclasses
_original_create_fn = dataclasses._create_fn
def _new_create_fn(name, args, body, **kwargs):
args_str = ', '.join(args)
body_str = '\n'.join(' ' + l for l in body)
print(f'def {name}({args_str}):\n{body_str}\n')
return _original_create_fn(name, args, body, **kwargs)
dataclasses._create_fn = _new_create_fn
@dataclasses.dataclass
class A:
x: int
y: int
显示如下内容:
def __init__(self, x:_type_x, y:_type_y):
self.x=x
self.y=y
def __repr__(self):
return self.__class__.__qualname__ + f"(x={self.x!r}, y={self.y!r})"
def __eq__(self, other):
if other.__class__ is self.__class__:
return (self.x,self.y,)==(other.x,other.y,)
return NotImplemented