【问题标题】:How did i access class methods via a variable which name as same as a method? [duplicate]我如何通过名称与方法相同的变量访问类方法? [复制]
【发布时间】:2016-09-01 03:28:44
【问题描述】:

有时我不知道用户会操作什么。

class User(object):
    ...

    def get_name(self):
        return self.name

    def get_age(self):
        return self.age

operation = "http://localhost:8080/user/get_name".split('/')[-1]
user = User(...)

如您所见,operation 是一个变量名,与类属性相同。

我试试:

eval('user.{}'.format(operation))

它可以运行。不过看起来很合适

现在我想通过user.operation这样的方式来处理它

我是怎么做到的?

【问题讨论】:

  • user.__getattribute__(operation)
  • 旁注:Python 不赞成 get_x 函数。允许直接访问属性(如果它们应该是可变的),或者将属性命名为 _name(以指示实现细节)并创建一个名为 name@property 函数,因此您可以通过 @987654330 访问@ 不需要括号。
  • 事实上,如果我的类Foo有一个名为get_name()的属性,mybey我会得到一个变量test,其值为get_name,所以我想通过@987654335执行它@。或许这不是很清楚的表达方式

标签: python


【解决方案1】:

您可以使用getattr()。像这样申请:

getattr(user, operation)()

所以现在,User 实例 user 将从字符串中调用 operation

getattr 将获取对象的属性,在这种情况下为user。然后它将执行user.operation,然后使用() 执行。

试试IDEOne

【讨论】:

  • 手动调用 __getattribute__ 并不像最初看起来那么好,因为 if you call __getattribute__ manually, you won't get the __getattr__ fallback。此外,foo.__getattribute__foo 是一个类时与foo 不是一个类时会做不同的事情。
  • @user2357112 你说得对,我应该编辑我的答案以排除__getattribute__吗?
  • 我会省略__getattribute__getattr 更适合通用的“从属性名称字符串获取属性值”工作。除非您覆盖它,否则您很少会想要调用 __getattribute__
  • @user2357112 好的,感谢您的建议!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 2020-10-03
  • 1970-01-01
  • 2020-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多