sweet_dreams吧 关注:37贴子:1,434
  • 1回复贴,共1

Subclass overrides superclass, use variable from superclass

只看楼主收藏回复

class Restaurant(object):
def __init__(self):
self.name = "Chez Lucy"
class SubRestaurant(Restaurant):
def __init__(self, *a, **kw):
super(SubRestaurant, self).__init__(*a, **kw)
self.dish = "Spam"
class ChildRestaurant(SubRestaurant):
def test(self):
print self.dish
my_restaurant = ChildRestaurant()
my_restaurant.test()


1楼2014-03-12 22:39回复
    # The output will be "Spam".
    # A subclass can access variables from the __init__() method of a superclass directly.
    # *a, **kw are used when a subclass needs to override a superclass:
    super(name of the subclass, self).method_name(*a, **kw)
    e.g.
    class SubRestaurant(Restaurant):
    def __init__(self, *a, **kw):
    super(SubRestaurant, self).__init__(*a, **kw)
    self.dish = "Spam"
    (superclass's __init__() method doesn't have variable self.dish)


    2楼2014-03-12 22:45
    回复