Python 访问父 class 变量作为子 class 中的实例变量

Python accessing parent class variable as instant variable in child class

我正在尝试访问父 class 的实例变量作为子 class 中的 class 变量。

目的是父 class 会有很多子 class 都需要有相同的结构,很多不同的人将使用和创建这些子 classes,不需要知道父 class 的内部工作原理。 这是我的例子:

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()

我希望能够创建父 class 人的子 class(在公司中一起构建),我只需要定义应该自动识别变量的查询变量 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__ 创建了 class 个变量...此查询在各个实例中始终相同:

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

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

将打印:

SELECT Jack FROM database_employee;
SELECT Jack FROM database_employee;