是否有一种标准方法将定义的所有参数传递__init__()给整个类(作为自参数)?
例如在我的程序中我通常这样做:
class DummyClass():
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
...
Run Code Online (Sandbox Code Playgroud)
有没有办法在不单独传递每个参数的情况下执行相同的操作?我想我曾经见过类似的事情super()。
根据这个答案,你可以这样做:
class X(object):
def __init__(self, x, y, z):
vars = locals() # dict of local names
self.__dict__.update(vars) # __dict__ holds and object's attributes
del self.__dict__["self"] # don't need `self`
Run Code Online (Sandbox Code Playgroud)
一个更Pythonic的答案是使用数据类
@dataclass
class X:
x: float
y: float
z: float
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |