开发者

In python, super() is always called first in a method. Are there situations where it should be called later?

开发者 https://www.devze.com 2023-02-24 05:41 出处:网络
Are there situations where you want to do some processing before you call super()? This is a contrived example.Are there better examples?Is this considered pythonic?

Are there situations where you want to do some processing before you call super()?

This is a contrived example. Are there better examples? Is this considered pythonic?

class Base(object):
    def __init__(self, name):
        print "Base %s created" % name
        self._name = name

c开发者_开发百科lass UpperBase(A):
    """ Similar to base but the name is in uppercase. """
    def __init__(self, name):
        name = name.upper() 
        super(UpperBase, self).__init__(name)


Sometimes you need to validate the arguments before calling super():

class UpperBase(Base):
    def __init__(self, name):
        if not name_valid(name):
            raise ValueError()
        super(UpperBase, self).__init__(name)

I don't see why this wouldn't be pythonic, because it's the easiest way to do it and it's straightforward. Also, read @JHSaunders' comment, he makes a good point.

0

精彩评论

暂无评论...
验证码 换一张
取 消