如何在Python中创建具有前缀属性的相同类? [英] How to create an identical class but with prefixed attributes in Python?

查看:150
本文介绍了如何在Python中创建具有前缀属性的相同类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个带有任意类A的函数,例如:

I would like to write a function that takes an arbitrary class A, for example:

class A(C, D, metaclass=E):
    x = 1
    def f(self): pass
    @classmethod
    def g(cls): pass
    @staticmethod
    def h(): pass

并返回与A相同但带有前缀属性的新类B,例如:

and that returns a new class B identical to A but with prefixed attributes, for example:

class B(C, D, metaclass=E):
    prefix_x = A.x
    prefix_f = A.f
    prefix_g = A.g
    prefix_h = A.h

我该怎么办?

推荐答案

经过反复试验,这是与@Maggyero共同努力的结果:

After trial and error, here is the result of the joint effort with @Maggyero:

def transform(cls, prefix='prefix_'):
     attrs = {key if key.startswith('__') else prefix+key: value 
              for key, value in cls.__dict__.items()}
     attrs['__class__'] = cls  # allow super() calls in methods of cls
     return cls.__class__(cls.__name__, cls.__bases__, attrs)

这篇关于如何在Python中创建具有前缀属性的相同类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆