python-3.x - 如何在 python def 中使用 self 设置默认参数?

标签 python-3.x

我试图调用 __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/

相关文章:

python - 在 CMD "python"启动 Python 3.3, "py"启动 Python 2.7,我该如何更改?

python - 根据条件删除嵌套列表中的列表

python - 我还是不明白内存观的意义

python - 矩阵与标量数组的 Numpy 乘法,没有 for 循环

python - Windows和Python3.7.4下RDKit安装

python-3.x - 使用Python文本搜索YouTube视频源代码

python - 尝试将列表添加到列表时出现 TypeError

python - PyAutoGUI 定位命令返回错误的图像识别坐标

python - 如何使用 Python 暂时禁用键盘输入

python - 如何迭代列表列表,同时将列表中的每个值传递到 API 并在每个列表列表之后暂停?