如何为 class 编写通用的 get 方法?
How to write general get methods for a class?
最近我开始在 python 中使用 oop。我想为启动的属性编写一个通用的 get 或 set 方法。例如,class 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)
我不确定这是否可能,因为我找不到任何东西。我怎样才能做到这一点?
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__ and https://docs.python.org/2/library/functions.html#getattr。
最近我开始在 python 中使用 oop。我想为启动的属性编写一个通用的 get 或 set 方法。例如,class 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)
我不确定这是否可能,因为我找不到任何东西。我怎样才能做到这一点?
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__ and https://docs.python.org/2/library/functions.html#getattr。