python - 无法访问继承的 Python 类中的父属性

标签 python inheritance

这是我的父类,

class BaseResource:
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        fmt = '[%(asctime)s] [%(levelname)s] [%(message)s] [--> %(pathname)s [%(process)d]:]'
        logging.basicConfig(format=fmt, level=logging.DEBUG)

    def log(self, msg):
        self.logger.debug(msg)

这是我继承的对象,

class SendOTP(BaseResource):

    def __init__(self):
        super(BaseResource, self).__init__()

    def on_post(self, req, res):
        self.logger.log("[FAILURE]..unable to read from POST data")

这会引发以下错误,

AttributeError: 'SendOTP' object has no attribute 'logger'

我在这里做错了什么。

最佳答案

应该是super(SendOTP, self),而不是super(BaseResource, self)

另外,如果这是 Python 3,您可以将其简化为 super();如果是 Python 2,还需要将 BaseResource 的声明改为

class BaseResource(object):

获得一个新式的类(class)。

关于python - 无法访问继承的 Python 类中的父属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48129863/

相关文章:

python - 导入错误:无法导入站点模块及其依赖项:没有名为站点的模块

python - 如何修改 python 中每个列表/元组中的第一个值?

C++类继承 "expected class-name"错误

python - 如何使用基类类型提示在函数中传递子类

python - Pandas dataframe ,使用 iloc 替换最后一行

python - 如何将数据列表映射到函数列表?

c# - 具有类型约束或基类参数的通用方法

ios - Swift 子类继承初始值设定项吗?

python - 在 Python 赋值运算符中使用逗号和下划线的含义?

java - 如何在子类中访问父类(super class)的 protected 方法?