我正在嘗試將父類的實體變數作為子類中的類變數來訪問。
目的是父類將有許多子類,它們都需要具有相同的結構,并且許多不同的人將使用并創建這些子類,而無需了解父類的內部作業原理. 這是我的例子:
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 的子類(在 Company 中一起構建),我只需要定義應該自動識別變數的查詢變數human_name和source.
我將如何使這盡可能簡單?這甚至可能嗎?非常感謝!
uj5u.com熱心網友回復:
因此,您需要實際實作該屬性。
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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/457355.html
標籤:Python python-3.x 遗产 实例变量 类变量
上一篇:在SpringAuthorizationServer(0.2.3 )中支持并發全堆疊MVC(session)認證以及無狀態JWT認證
