简体   繁体   English

Python - 如何从派生的 class 更新基础 class 变量

[英]Python - How to update base class variable from derived class

I'm new to OOP, but experienced in SQL.我是 OOP 的新手,但在 SQL 方面经验丰富。 I'm writing a Luigi ETL task to generate reports.我正在编写一个 Luigi ETL 任务来生成报告。

I have a base class called Report, and 3 subclasses Report_Daily, Report_Weekly & Report_Monthly, which dynamically set the base class' SQL query's GROUP BY, so that the appropriate reports can be generated我有一个名为 Report 的基础 class,以及 3 个子类 Report_Daily、Report_Weekly 和 Report_Monthly,它们动态设置基类的 SQL 查询的 GROUP BY,以便生成相应的报告

#reports.py

class Report:
    report_sql = {'daily':'day', 'weekly':'firstdayofweek(day)', 'monthly':'firstdayofmonth(day)'}
    @property
    def report_type(self):
        return '' # To be instantiated by subclass
    sql = 'select '+report_sql[report_type]+' count(*) from employees group by '+report_sql[report_type]
    def run(self):
        #code that runs sql query

class ReportDaily(Report):
    report_type = 'Daily'

class ReportWeekly(Report):
    report_type = 'Weekly'

class ReportMonthly(Report):
    report_type = 'Monthly'

These 3 subclasses are then scheduled via Luigi & Chronos like然后通过 Luigi & Chronos 安排这 3 个子类,例如

luigi --module etl.reports ReportDaily
luigi --module etl.reports ReportWeekly
luigi --module etl.reports ReportMonthly

But I'm getting 'Cannot concatenate string and property' error.但我收到“无法连接字符串和属性”错误。 I tried setting report_type as a luigi parameter, but get similar error.我尝试将 report_type 设置为 luigi 参数,但得到类似的错误。
What is the proper design pattern to achieve this?实现这一目标的正确设计模式是什么?

In Python, if you do this:在 Python 中,如果您这样做:

class Report:
    report_sql = "bla"

report_sql will be a class variable. report_sql将是一个 class 变量。 More info in Python docs (Class and Instance Variables) . Python 文档(类和实例变量)中的更多信息。 Because you want to change it in your classes it is better it be an instance variable (unique to each instance).因为你想在你的类中改变它,所以最好是一个实例变量(每个实例都是唯一的)。

Also, I think the Report class needs to be an abstract base class (ABC).另外,我认为Report class 需要是一个抽象基础 class (ABC)。 Check the docs for more info: abc — Abstract Base Classes .查看文档以获取更多信息: abc — 抽象基类 Because technically, Abstract Classes shouldn't be instantiated, my __init__ method has the abstractmethod decorator.因为从技术上讲,抽象类不应该被实例化,所以我的__init__方法有abstractmethod装饰器。 As you can read, the ReportDaily , ReportWeekly and ReportMonthly classes call the constructor of the base class with the needed report_type .如您所见, ReportDailyReportWeeklyReportMonthly类使用所需的report_type调用基本 class 的构造函数。

I only keep the part related to the report type and the SQL query.我只保留与报告类型和 SQL 查询相关的部分。 This is my new code:这是我的新代码:

from abc import ABC, abstractmethod


class Report(ABC):
    @abstractmethod
    def __init__(self, report_type):
        self.report_type = report_type
        self.sql = f'select {self.report_type} count(*) ' \
                   f'from employees ' \
                   f'group by {self.report_type}'

    def run(self):
        ...


class ReportDaily(Report):
    def __init__(self):
        super().__init__(report_type='Daily')


class ReportWeekly(Report):
    def __init__(self):
        super().__init__(report_type='Weekly')


class ReportMonthly(Report):
    def __init__(self):
        super().__init__(report_type='Monthly')


daily_report = ReportDaily()
print(daily_report.sql)
weekly_report = ReportWeekly()
print(weekly_report.sql)
monthly_report = ReportMonthly()
print(monthly_report.sql)
try:
    Report(report_type="dummy")
except TypeError:
    print("an abstract class cannot be instantiated!")

output: output:

select Daily count(*) from employees group by Daily
select Weekly count(*) from employees group by Weekly
select Monthly count(*) from employees group by Monthly
an abstract class cannot be instantiated!

Notes:笔记:

  • I use f-strings for string formatting.我使用f-strings进行字符串格式化。
  • SQL Alchemy is a good library for handling SQL in Python SQL Alchemy是一个很好的库,用于处理 Python 中的 SQL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM