我试图访问父类的实例变量作为子类中的类变量.

其目的是父类将有许多子类,这些子类都需要具有相同的 struct ,许多不同的人将使用和创建这些子类,而不需要知道父类的内部工作方式.

class Human(ABC):

    def __new__(cls, *args, **kwargs):
        cls.human_name = args[0]
        cls.source = f'database_{cls.__name__}'.lower()
        return super().__new__(cls)

    @property
    @abstractmethod
    def query(self):
        pass


class Company:
    class Employee(Human):
        query = f'SELECT {human_name} FROM {source};'

        # these two functions are just for testing and will not be in the final product
        def print_something(self):
            print(self.human_name)

        def print_source(self):
            print(self.source)


e = Company.Employee('John')
print(e.human_name)
print(e.query)
e.print_source()

我希望能够创建父类Human的子类(在公司中一起构建),其中我只需要定义查询变量,该变量应自动识别变量human_namesource.

我该如何让这件事尽可能简单?这可能吗?

推荐答案

因此,您需要实际实现该属性.

class Human(ABC):

    def __new__(cls, *args, **kwargs):
        cls.human_name = args[0]
        cls.source = f'database_{cls.__name__}'.lower()
        return super().__new__(cls)

    @property
    @abstractmethod
    def query(self):
        pass


class Company:
    class Employee(Human):
        @property
        def query(self):
            return f'SELECT {self.human_name} FROM {self.source};'

        # these two functions are just for testing and will not be in the final product
        def print_something(self):
            print(self.human_name)

        def print_source(self):
            print(self.source)


e = Company.Employee('John')
print(e.human_name)
print(e.query)
e.print_source()

但是请注意,由于__new__创建类变量...此查询在多个实例中始终相同:

employee1 = Company.Employee('John')
employee2 = Company.Employee('Jack')

print(employee1.query)
print(employee2.query)

将打印:

SELECT Jack FROM database_employee;
SELECT Jack FROM database_employee;

Python相关问答推荐

Django:如何将一个模型的唯一实例创建为另一个模型中的字段

云上Gunicorn的Flask-socketIO无法工作

FastAPI:使用APIRouter路由子模块功能

带有pandas的分区列上的过滤器的多个条件read_parquet

"Discord机器人中缺少所需的位置参数ctx

使用图片生成PDF Django rest框架

根据给定日期的状态过滤查询集

如何在具有重复数据的pandas中对groupby进行总和,同时保留其他列

重新匹配{ }中包含的文本,其中文本可能包含{{var}

运行总计基于多列pandas的分组和总和

更改键盘按钮进入'

当从Docker的--env-file参数读取Python中的环境变量时,每个\n都会添加一个\'.如何没有额外的?

无法定位元素错误404

try 将一行连接到Tensorflow中的矩阵

在极性中创建条件累积和

如果满足某些条件,则用另一个数据帧列中的值填充空数据帧或数组

如何从列表框中 Select 而不出错?

如何创建引用列表并分配值的Systemrame列

导入错误:无法导入名称';操作';

交替字符串位置的正则表达式