继承中名称空间的顺序是什么?

时间:2015-07-29 01:22:09

标签: python inheritance namespaces name-mangling

派生类可以隐式访问其基类成员函数,除非我弄错了。派生类也可以通过对它们进行前缀调用来访问其基类的属性:BaseClass.base_attribute。但我似乎不明白派生类的实例如何使用基类的方法。例如:

class Visitor():
    """ Interface to Visitor

    provide an interface to visitors that
    perform an operation on a data collection """

    def visitProduce():
        pass
    def visitMeat():
        pass
    def visitBakedGoods():
        pass
    def visitDairy():
        pass
    def visitNonFood():
        pass



class PriceVisitor(Visitor):
    __cost = 0.0        # total cost of groceries

    def __init__(self):
        self.__cost = 0.0
    def visitProduce(self, p):
        self.__cost += p.price()
    def visitMeat(self, m):
        self.__cost += m.price()
    def visitBakedGoods(self, b):
        self.__cost += b.price()
    def visitDairy(self, d):
        self.__cost += d.price()
    def visitNonFood(self, nf):
        self.__cost += nf.price()


class Groceries():
    shopping_cart = []      # list of grocery items

    def Groceries(self):
        self.shopping_cart = []     
    def addProduce(self, p):
        pass
    def addMeat(self, m, lb):
        pass
    def addBakedGoods(self, b):
        pass
    def addDairy(self, d):
        pass
    def addNonFood(self, nf):
        pass
    def accept(self, v):
        pass
    def getShoppingCart(self):
        print(self.shopping_cart)
    def calculateCost(self, v):
        for item in self.shopping_cart:
            item.accept(v)
            item.details()
            print('Total cost is: $', v.__cost)



class Produce(Groceries):
    def addProduce(self):
        Groceries.shopping_cart.append(self)

    def accept(self, v):
        v.visitProduce(self)

    def price(self):
        return self.__price

    def details(self):
        print(self.__name, ' for: $', self.__price + '')



class Apples(Produce):
    __name = None
    __price = 3.25

    def __init__(self, name):
        self.__name = name

这是对Apple,Produce,Groceries和PriceVisitor类的测试

import VisitorPattern as vp

def main():
    # Visitor object
    my_visitor = vp.PriceVisitor()

    # Grocery object stores objects in its shopping_cart attribute
    my_groceries = vp.Groceries()

    # Add items
    red_apple = vp.Apples('red apple')
    gold_apple = vp.Apples('gold apple')
    red_apple.addProduce()
    gold_apple.addProduce()

    my_groceries.getShoppingCart()

    my_groceries.calculateCost(my_visitor)

if __name__ == '__main__':
    main()

现在,我理解它的方式是,在构建Apple实例时,它可以访问Produce的方法price()。使用Apple类的实例调用此方法将传递其自己的实例来代替'self'。然后程序返回属于调用方法的实例的__price属性的值,在本例中为Apple。但是,我收到了这个错误:

C:\Users\josep_000\Documents\School\Summer 2015\Python Assignment 4>python test.
py
[<VisitorPattern.Apples object at 0x026E0830>, <VisitorPattern.Apples object at
0x026E0910>]
Traceback (most recent call last):
  File "test.py", line 23, in <module>
    main()
  File "test.py", line 20, in main
    my_groceries.calculateCost(my_visitor)
  File "C:\Users\josep_000\Documents\School\Summer 2015\Python Assignment 4\Visi
torPattern.py", line 60, in calculateCost
    item.accept(v)
  File "C:\Users\josep_000\Documents\School\Summer 2015\Python Assignment 4\Visi
torPattern.py", line 71, in accept
    v.visitProduce(self)
  File "C:\Users\josep_000\Documents\School\Summer 2015\Python Assignment 4\Visi
torPattern.py", line 28, in visitProduce
    self.__cost += p.price()
  File "C:\Users\josep_000\Documents\School\Summer 2015\Python Assignment 4\Visi
torPattern.py", line 74, in price
    return self.__price
AttributeError: 'Apples' object has no attribute '_Produce__price'

绑定和命名空间如何在继承中实际工作?我可以在每个Produce的派生类中编写price()方法,但这会破坏继承点。我认为我的问题还源于名称修改,但仍然不知道如果我不使我的属性“私有”会发生什么。澄清会很棒。感谢

修改

我宣布Groceries的构造函数错误:

# Wrong way
def Groceries(self):   
    self.shopping_cart = []

# Should be
def __init__(self):
    self.__shopping_cart = []

全职工作和晚上的家庭作业的产物

3 个答案:

答案 0 :(得分:2)

  

继承中名称空间的顺序是什么?

Python使用Method Resolution Order来查找绑定到该对象实例的方法。

它还会调用名称修改,这就是找不到方法_Produce__price的原因。您正在尝试使用.__price但是当它被继承时,Python会将该类的名称添加到名称的前面。不要使用两个下划线,将两个下划线更改为一个,并且您的代码将按预期工作,并且您将始终查找._price,这将不会调用名称修改。

有关详细信息,请参阅文档:

https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references

答案 1 :(得分:0)

并非真正直接回答您的所有问题,但我希望以下代码能够阐明如何在Python中进行继承。

class Produce(object):

    def __init__(self, name=None, price=None):
        self.__name = name
        self.__price = price

    def __str__(self):
        return self.__name

    @property
    def bulk_price(self):
        return self.__price * 100

class Apple(Produce):

    def __init__(self, name="Apple"):
        self.__name = name
        self.__price = 3.25
        super(self.__class__, self).__init__(self.__name, self.__price)

a = Apple("Gold Apple")
print a
print a.bulk_price
# Gold Apple
# 325.0

正如您所看到的,我在两个课程中都无法访问nameprice。这样,我就不能明确地称它们为a.__price。通过在子类中使用super,我可以避免在仍然可以访问其方法的情况下进一步引用基类

答案 2 :(得分:0)

我看到了你的错误,你的父母需要调用孩子的功能,但是你没有将孩子转移到父母,所以它会得到错误。现在我举个例子:

class A:
    def __init__(self, handler):
        self.a = 5
        self.real_handler = handler

    def get(self):
        print "value a = %d"%self.a
        self.real_handler.put()

class B(A):
    def __init__(self):
        A.__init__(self, self)    ##transport B to A
        self.b = 3

    def get(self):
        print "value b is %d"%self.b
        A.get(self)

    def put(self):
        self.b = 6
        print "value b change into %d"%self.b

if __name__=="__main__":
    b = B()
    b.get()

在父B中,它将调用孩子A的功能put()。我希望这可以帮到你。