我试图调用 __init__
变量作为默认变量,但它没有调用
class test1:
def __init__(self,name):
self.name = name
def method1(self,name2=self.name):
return name2
如果我调用该函数,例如
from test import test1
ma = test1("mkHun")
va = ma.method1() # Here I am expected output is mkhun
ca = ma.method1("new name")
在 JavaScript 中,此功能称为 default parameters 。这个功能在Python中可用还是我的代码有问题?
最佳答案
这是实现类似功能的一种方法。其他人可能有更Pythonic的方式。代码灵感来自docs here
class test1:
def __init__(self, name):
self.name = name
def method1(self, newName=None):
if newName is not None:
self.name = newName
return self.name
ma = test1("mkHun")
va = ma.method1() # Here I am expected output is mkhun
print(va)
ca = ma.method1("new name")
print(ca)
关于python-3.x - 如何在 python def 中使用 self 设置默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48941316/