繁体   English   中英

识别类属性类型并调用其函数

[英]Identify class attribute type and call its function

我定义了一个Field类。 我还定义了AB ,它们是Field子类。

现在,我定义了另一个Tool类。 它可以包含类变量,该类变量可以是Field类或其他类,也可以是普通变量。 如果变量的类型为Field则调用fun1并收集结果。

请提出我可以采取的任何方法。 我是面向对象编程的新手。

class Field(object):
  def fun1(self):
    return 'Field'

class A(Field):
  def fun1(self):
    return 'A fun1'

class B(Field):
  def fun1(self):
    return 'B fun1'

class Tool(object):
  a1 = A()
  b1 = B()
  c1 = 'abc'

  def fun1(self):
    all_attributes = dir(self)
    result_list = []
    for attribute in all_attributes:
      if attribute is of type Field:
        result_list.append(attribute.fun1())
  return return_list

我认为您正在寻找内置的isinstance

if isinstance(attribute, Field):
    ...

或可能:

if isinstance(getattr(self, attribute), Field):
    ...

因为看起来attribute可能是代码中属性的字符串名称。

应该注意的是,通常最好构造数据,使其包含所有同类型。 然后,您不需要进行任何类型检查等操作-尽管很难说该建议是否对您在问题中发布的通用示例代码有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM