例如,如果我想创建一个名为“Clinical\u triads”的类,我可以将*args作为一个参数来指示任意数量的参数吗?然后我会把它作为参数变量吗
class Clinical_triads:
""" Clinical S&Sx of medical triads """
def __init__(self, SSx_1, SSx_2, SSx_3, *args):
""" Initialize SSx_1, SSx_2, SSx_3 of clinical signs """
self.SSx_1 = SSx_1
self.SSx_2 = SSx_2
self.SSx_3 = SSx_3
self.additional_SSx = args # is this variable needed?
def SSx1(self):
""" Print the first clinical sign or symptom"""
return f"{self.SSx_1.title()}"
def SSx2(self):
""" Print the second clinical sign or symptom"""
return f"{self.SSx_2.title()}"
def SSx3(self):
""" Print the third clinical sign or symptom"""
return f"{self.SSx_3.title()}"
在您的案例中,似乎需要指定3个关键症状(“三联症”)。如果您想使用
*args
来传递、记住和重用其他(可变数量)症状,那么肯定yes您需要将它们存储为Clinical_triads
的属性(它们将存储为tuple
)。如果不这样做就将*args
传递给__init__()
,这只意味着可以将尽可能多的参数传递给Clinical_triads
,而不会导致TypeError
,但是超过3个指定关键字的参数将是无意义和无法恢复的正如评论中所说,您现在没有对附加参数做任何操作,但是(例如)您可以说添加一个打印附加症状的方法:
我认为有几个类似的选择,你可能可以考虑什么是你想要实现的最好的。您还可以为“附加症状”使用另一个关键字参数,默认为空数组。或者,您只能使用
*args
并根据传递的顺序推断它们的重要性(并分配像SSx_#
这样的属性)但是,是的,在类中使用
*args
或**kwargs
是有效的,并且是有用的。下面是在函数定义中使用*args
的典型解释示例:我认为这仅仅取决于您想要与类关联的信息以及您想要如何检索它
相关问题 更多 >
编程相关推荐