Python 2.7惯性获取父方法属性

2024-09-27 19:31:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个新手,对在python上学习OOP感到困惑。我也尝试使用super继承类,但它并没有按预期工作

这是我的密码

parent.py

class Sale(http.Controller):

    def cart(self, **post):
        order = request.website.sale_get_order()
        ....
        return request.render("website_sale.cart", values)

child.py

import Sale as sale

class SaleExtend(sale):

    def cart(self, **post):
        if order:
        # do something
    ....

    return super(SaleExtend, self).cart(**post)

我犯了个错误

AttributeError: 'Sale (extended by SaleExtend)' object has no attribute 'order'

如果我只是正确地使用pass,那么如何从父级获取order值呢

或者我做错了


Tags: pyselfreturnrequestdeforderwebsitesale
1条回答
网友
1楼 · 发布于 2024-09-27 19:31:16

您既没有实例也没有类变量order

class Sale(http.Controller):

    def cart(self, **post):
        # FUNCTION SCOPE - exists only inside the function
        order = request.website.sale_get_order()  
        ....
        return request.render("website_sale.cart", values)

类变量的创建方式如下:

class Ale():
    content = "Lager"     # this is shared between all instances -> "static"

实例变量的创建方式如下:

class Ale():
    def __init__(self, ale_type):
        self.content = ale_type       # this is different for each instance unless you 
                                      # create multiple instances with the same ale_type
                                      # but they are still "independent" of each other

函数范围变量如下所示:

class Ale():

    # ....

    def doSomething(self):
        lenContent = len(self.content)      # function scope
        print( self.content, lenContent )

    def doElse(self):
        print(lenContent)   # NameError - does not exist in scope

Resolution of namesShort description of the scoping rules?

相关问题 更多 >

    热门问题