python - python中使用类方法修改对象的属性

标签 python

我试图使用类中定义的方法来稍后修改由该类创建的对象的属性,但似乎存在一个对我来说并不明显的范围问题。采取以下代码:

class Test:
    def __init__(self, attribute):
        self.attribute = attribute
    def change_attrib(self, attribute, value):
        if attribute + value < 0: attribute = 0
        else: 
            attribute += value
            print(str(attribute) + ' This is inside the method')

test1 = Test(10)

print(str(test1.attribute) + " This is before running the method")

test1.change_attrib(test1.attribute, 10)

print(str(test1.attribute) + " This is after running the method")

test1.attribute += 20

print(str(test1.attribute) + " This is after modifying the attribute directly")

运行此代码会产生以下结果:

10 This is before running the method
20 This is inside the method
10 This is after running the method
30 This is after modifying the attribute directly

所以看来,即使我在调用该方法时明确引用了我想要更改的实例,该方法中发生的所有事情都保留在该方法中。

我可以看到直接修改属性是有效的,但我想防止负值(因此是该方法)。我还知道我可以在方法中使用内置的 setattr() 函数,这也有效,但要求我在将属性传递到方法之前将属性的语法更改为字符串,而且我更喜欢显式引用到属性。最后,我真的很想了解这里发生了什么。

编辑: 这是基于 rdvdev2 提示的工作代码。我只需要引用 self 来设置实例的值:

class Test:
def __init__(self, attribute):
    self.attribute = attribute
def change_attrib(self, attribute, value):
    if attribute + value < 0: attribute = 0
    else: 
        attribute += value
        self.attribute = attribute
        print(str(attribute) + ' This is inside the method')

同时感谢 kindall 对所发生事情的精彩解释。

最后的扩展:上面的代码实际上仅在属性名为 attribute 时才有效。我想大家已经更好地掌握了我在这里需要的东西;为了使用该函数修改对象的任何属性,我需要某种方法来引用所需的属性。由于 python 似乎传递的是一个值而不是引用,所以我必须以某种方式获取引用,而对我现有代码影响最小的方式似乎是使用 get/setattr....所以我打破了正则表达式并更改了 160+引用文献。

最佳答案

当您将 test1.attribute 传递给 change_attrib() 时,方法内 attribute 的值不是指向 的指针>test1.attribute 可用于更改其值。它是整数 10。然后将参数 value 添加到 attribute,生成 attribute 等于 20。然后该方法结束,值属性消失。 test1.attribute 的值从未改变,因为您从未更改过它。

如果您希望您的方法修改任何属性,您可以将其名称作为字符串传递。然后,您可以使用 getattr()setattr() 来获取和设置属性。

def change_attrib(self, name, value):
        attribute = getattr(self, name)
        if attribute + value < 0: attribute = 0
        else: 
            attribute += value
            print(str(attribute) + ' This is inside the method')
        setattr(self, name, attribute)

test1.change_attrib("attribute", 10)

关于python - python中使用类方法修改对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55621639/

相关文章:

python - 当测试的函数是 Click 命令时 pytest 失败

python - 在 skimage 中找不到度量标准的模块。其他都ok

python - 如何在python中获取当前网页的URL?

python - 如何将日期列添加到Python中已有的时间列?

python - 追加 CSV 文件,匹配无序列

python - 如果删除了子项,则删除父项

python - 异常: error while installing jupyter on Ubuntu

Python httplib2 "httplib2.SSLHandshakeError"

python - 如何正确查询/格式化日期

python - "OSError: telling position disabled by next() call"错误的含义?