Python - 一种一次性导出或修改所有类对象属性与值的方法

这篇博客介绍了如何在Python中动态访问和修改类对象的属性,即使属性名未知。通过实例`Article`展示了如何使用`__dict__`属性导出所有非方法属性,并以字典形式存储。此外,还提供了`outputAttrs`和`inputAttrs`方法,用于输出和重新设置类的属性值。在测试部分,展示了如何添加新属性并进行输入,最后打印了新增属性的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文

转载请注明出处:首发于CSDN

访问一个已知属性名的属性很简单,a.name就完事了,然而访问不知名的属性却相对麻烦(大概不会有码农不知道自己的类里都有什么属性吧)。以防万一,写了一点东西提供一个思路。

该方法可以以键值对(字典)形式导出该类下所有属性及对应值,不会导出方法或者别的什么东西,比较方便。

相似地,也可以用一个键值对(需要保存在类对象的一个临时属性中,当然,修改成方法的参数形式难度也不大)对此进行修改。

代码如下:

# Reference 1: http://c.biancheng.net/view/2374.html
class Article():
    def __init__(self):
        self.sample1 = ['abc']
        self.sample2 = 0xFF
        self.sample3 = '@ClementLevi'
        self._content = {} # 临时容器,届时不纳入考虑范围内

    def outputAttrs(self):
        for attr in self.__dict__: # __dict__属性(一个字典)不会包含父类属性和各种方法,因而十分好用
            if attr != '_content': # 不导出临时容器,避免递归
                self._content.update({attr: self.__dict__[attr]}) #此处借鉴参考文献1,实际上并不完全相同;而且后文中修改值的手段也与我此处所写的有很大区别
        print(self._content)

        return 0

    def inputAttrs(self):
        for attr in self._content.keys(): # dict.keys()会返回一个'dict_keys'类型对象,使用for遍历即可获取各字符串
        # 此处需要注意,临时容器的名称被写死,不过修改难度不大
            setattr(self, attr, (self._content)[attr]) # 使用setattr()函数设置属性值
        return 0
        
# 测试
if __name__ == "__main__":
    a = Article()
    print(a.outputAttrs())

    a._content = {"What":114514}
    print(a.outputAttrs())
    a.inputAttrs()
    print(a.What)

参考了一点点C语言中文网上的东西,不过不多,而且实现手段也不同。参考文献URL见代码首行和文末。

参考文献:
[1]:Python __dict__属性:查看对象内部所有属性名和属性值组成的字典

English Version

Translated by myself from Chinese version. If confused, please refer to the original text.

To acquire attributes of a class object when knowing their names is quite simple – an “a.name” can do. But it is not the case when the names remain unknown (I suppose few can be so careless to forget the names!). In case, here goes a way to solve this problem.

This example shows how key-value pairs about attributes can be digested from a class object without outputting “method” and other things.

Correspondingly, a key-value pair can modify those attributes as well, as long as it is written into a temporary attribute, which can surely be modified into a parameter of this method for other purpose.

The code is as follows:

# Reference 1: http://c.biancheng.net/view/2374.html
class Article():
    def __init__(self):
        self.sample1 = ['abc']
        self.sample2 = 0xFF
        self.sample3 = '@ClementLevi'
        self._content = {} # Temporary container which won't output

    def outputAttrs(self):
        for attr in self.__dict__: # __dict__ won't contain father_class attributes or methods, making it quite convenient
            if attr != '_content': # Do not output the temp container in case of recursion
                self._content.update({attr: self.__dict__[attr]}) # Referred to reference_1 but not actually the same. The modification later on is not a same way as well
        print(self._content)

        return 0

    def inputAttrs(self):
        for attr in self._content.keys(): # dict.keys() returns a 'dict_keys' object,which can use 'for' upon for each string
        # Attention: the container's name is written, but can certainly be changed when you use this code
            setattr(self, attr, (self._content)[attr]) # use "setattr()" to set values
        return 0
        
# testing
if __name__ == "__main__":
    a = Article()
    print(a.outputAttrs())

    a._content = {"What":114514}
    print(a.outputAttrs())
    a.inputAttrs()
    print(a.What)

Not too much reference, and without the same technique to make this.
Reference:
[1]:Python __dict__属性:查看对象内部所有属性名和属性值组成的字典

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值