python setattr使用示例,pythonsetattr示例,python中可以使用s


python中可以使用setattr给对象添加属性或者方法

如下示例代码:

class Song:    """The class to store the details of each song"""    attsToStore=('Name', 'Artist', 'Album', 'Genre', 'Location')    def __init__(self):        for att in self.attsToStore:            setattr(self, att.lower(), None)    def setDetail(self, key, val):        if key in self.attsToStore:            setattr(self, key.lower(), val)

评论关闭