Python 访问基类(父类)方法中的类属性时,派生类(子类)可能会重载

Python 访问基类(父类)方法中的类属性时,派生类(子类)可能会重载,python,class,parent-child,static-variables,static-classes,Python,Class,Parent Child,Static Variables,Static Classes,我试图在父类中创建一个函数,该函数引用任何子类最终调用的函数,以获取子类中的静态变量 这是我的密码 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): at

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

这是我的密码

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
类元素:
属性=[]
def属性_到_字符串():
#做点什么
返回“|”。join(_uclass_uu.attributes)#与应该可以工作

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
我们应该一起工作

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

实例方法的第一个参数应该是
self
。如果它们是静态的,那么应该有decorator。函数是静态的,不需要
self
。您希望如何从静态方法获取类字段
属性
?它应该是类方法(修饰为),我以前从未使用过
staticmethod
decorators。让我检查一下。实例方法的第一个参数应该是
self
。如果它们是静态的,那么应该有decorator。函数是静态的,不需要
self
。您想如何从静态方法中获取类字段
属性
?它应该是类方法(修饰为),我以前从未使用过
staticmethod
decorators。让我看看。