如何为类编写通用get方法?

2024-06-02 08:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

最近我开始在python中使用oop。我想为初始化的属性编写一个通用的get或set方法。例如,类Song具有多个属性和相应的get方法。我想避免使用多个if语句。只有两个属性并不重要,但是如果有>;5个属性,代码将很难读取。是否可以使用args中的字符串从init获取值,而不定义所有可能的情况?你知道吗

class Song(object):

    def __init__(self,title,prod):
        self.title = title
        self.prod = prod

    def getParam(self,*args):
        retPar = dict()
        if 'title' in args: 
            print(self.title)
            retPar['title'] = self.title
        if 'prod' in args:
            print(self.prod)
            retPar['prod'] = self.prod
        return(retPar)

我不确定,如果这是可能的,因为我找不到任何东西。我该怎么做?你知道吗


Tags: 方法inselfgetif属性songtitle
1条回答
网友
1楼 · 发布于 2024-06-02 08:25:00

provide a function for colleagues who are not familiar with the python syntax, such that they do not have to access the the attritubes directly. For plotting and such things

because python is not necessarily taught and the dot syntax is confusing for people who have basic knowledge in matlab

我认为这是很容易教出来的,你不应该为了这么简单的事情而弯腰…但是假设这真的是你想要的,这看起来是个更好的主意:

class Song(object):
    def __init__(self, title, prod):
        self.title = title
        self.prod = prod

    def __getitem__(self, key):
        return getattr(self, key)

song = Song('Foo', 'Bar')
print song['title']

https://docs.python.org/2/reference/datamodel.html#object.__getitem__https://docs.python.org/2/library/functions.html#getattr。你知道吗

相关问题 更多 >