Python 在创建没有构造函数的实例时,是否可以设置类的属性?
在Python中,如果我有一个Python 在创建没有构造函数的实例时,是否可以设置类的属性?,python,Python,在Python中,如果我有一个类 class Rectangle: x:int = 0 y:int = 0 width:int = 0 height:int = 0 有没有一种方法可以在没有构造函数的情况下创建它的实例并同时设置所有属性 比如(显然不起作用): 我知道字典,所以我愿意接受建议 编辑 我知道我能做到 class Rectangle: def __init__(x:int = 0, y:int = 0, width:int = 0, height:int
类
class Rectangle:
x:int = 0
y:int = 0
width:int = 0
height:int = 0
有没有一种方法可以在没有构造函数的情况下创建它的实例并同时设置所有属性
比如(显然不起作用):
我知道字典,所以我愿意接受建议
编辑
我知道我能做到
class Rectangle:
def __init__(x:int = 0, y:int = 0, width:int = 0, height:int = 0):
self.x = x
self.y = y
self.width = width
self.height = height
但这并不是一个很好的解决方案,当类包含十几个属性时,会有很多重复
正如在评论中所读到的,这似乎是一条路。我怀疑一个使用\uuuu init\uuuu
的类会做你想做的事情(有点不清楚)。请注意,您只使用类变量定义了一个类。类似这样的情况更为典型:
class Rectangle:
def __init__(self, x:int=0, y:int=0, width:int=0, height:int=0):
self.x = x
self.y = y
self.width = width
self.height = height
# instantiation:
rect = Rectangle() # uses defaults
rect = Rectangle(x=1,y=2,width=3,height=4) # create instance and set attributes as you say
这是香草味的。替代方法包括attrs
库或一个dataclass
读取行之间的数据,您可能正在查找dataclass:最后一行本质上是对构造函数的调用。为什么要避免构造函数调用?还要注意如何定义类,这些是类属性,而不是实例属性。这是否回答了您的问题?你的意思是不想调用构造函数,还是不想手动编写构造函数?是的,我知道这一点,但我提供了一个简单的示例。我的实际类有许多属性,在构造函数中复制所有属性是愚蠢的。我更喜欢声明class属性,然后不带参数直接重写它们。(我已更新问题以解释这一点)
class Rectangle:
def __init__(self, x:int=0, y:int=0, width:int=0, height:int=0):
self.x = x
self.y = y
self.width = width
self.height = height
# instantiation:
rect = Rectangle() # uses defaults
rect = Rectangle(x=1,y=2,width=3,height=4) # create instance and set attributes as you say