【问题标题】:Accessing class attributes in base (parent) class method with possible overloading by derived (children) classes访问基(父)类方法中的类属性,派生(子)类可能重载
【发布时间】:2017-10-30 08:43:40
【问题描述】:

我正在尝试在父类中创建一个函数,该函数引用最终调用它的子类,以获取子类中的静态变量。

这是我的代码。

class Element:
  attributes = []

  def attributes_to_string():
    # do some stuff
    return ' | '.join(__class__.attributes) # <== This is where I need to fix the code.

class Car(Element):
  attributes = ['door', 'window', 'engine']

class House(Element):
  attributes = ['door', 'window', 'lights', 'table']

class Computer(Element):
  attributes = ['screen', 'ram', 'video card', 'ssd']

print(Computer.attributes_to_string())

### screen | ram | video card | ssd

如果它是使用self.__class__ 的类的实例,我知道我会怎么做,但是在这种情况下没有self 可以引用。

【问题讨论】:

  • 实例方法的第一个参数应该是self
  • 如果是静态的,应该有staticmethod装饰器
  • 函数是静态的,不需要self
  • 你想如何从静态方法中获取类字段attributes?它应该是类方法(用classmethod装饰)然后
  • 我以前从未使用过 staticmethod 装饰器。让我看看。

标签: python class parent-child static-variables static-classes


【解决方案1】:

decoratingclassmethod 应该可以工作

class Element:
    attributes = []

    @classmethod
    def attributes_to_string(cls):
        # do some stuff
        return ' | '.join(cls.attributes)


class Car(Element):
    attributes = ['door', 'window', 'engine']


class House(Element):
    attributes = ['door', 'window', 'lights', 'table']


class Computer(Element):
    attributes = ['screen', 'ram', 'video card', 'ssd']


print(Computer.attributes_to_string())

给我们

screen | ram | video card | ssd

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多