我正在学习 python OOP,并且真的很困惑何时使用 self
和不使用。
特别是当我想要创建一个默认获取对象实例输入的方法,并且还想让它作为可以获取自定义参数输入的普通方法工作时,
对于方法的所有参数,输入 if x is None: x = self.x
有点麻烦。
示例如下。
from dataclasses import dataclass
@dataclass
class PlusCalculator():
x: int = 1
y: int = 2
result: int = None
def plus(self, x=None, y=None):
if x is None: x = self.x ## the bothersome part
if y is None: y = self.y
result = x + y
self.result = result ## also confusing...is it good way?
return result
pc = PlusCalculator()
print(pc.plus())
print(pc.plus(4,5))
有什么好的方法可以使用实例变量作为函数参数的默认值吗?
最佳答案
条件表达式可读、快速且直观 -
x = self.x if x is None else x
回复:
Is there any good way to use instance variables as default value of function parameter??
关于self.result
的设置 - 应该避免这种情况,除非您稍后需要将其作为实例变量访问。因此,您可以将其简化为:
@dataclass
class PlusCalculator():
...
def plus(self, x=None, y=None):
x = self.x if x is None else x
y = self.y if y is None else y
return x + y
关于python - 有没有什么很酷的方法在 python 类中表达 `if x is None: x = self.x` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77428302/