【问题标题】:How to extend parent __init__ when child uses more arguments than parent in python [duplicate]当孩子在python中使用的参数多于父级时如何扩展父级__init__ [重复]
【发布时间】:2015-04-19 16:50:24
【问题描述】:

例如我有 Link 类:

class link(object):
    def __init__(self, url, title, visited=False):
        self.url = url
        self.title = title
        self.visited = visited

我想将它扩展到 ArticleLink 类,它还有一个字段 - 日期(伪代码):

class articleLink(link):
    def __init__(self,<i want to avoid typing it all again>, date):
        super(articleLink, self).__init__(<what to type here?>)
        self.date = date

我在想什么错/如何正确地做到这一点?

【问题讨论】:

  • 您有很多选择(例如,使用 *args**kwargs),但我认为最好是明确并输入它们。

标签: python oop arguments init


【解决方案1】:

你可以这样做:

# Note this function requires exactly three arguments
def my_method(x,y,z):
    print 'x: %s, y: %s, z: %s'

class MyClass:
    def __init__(self, *my_args ):
        my_method( *my_args )


myClass = MyClass( 'x', 'y', 'z' )
# will print "x: x, y: y, z:z"

但这有点神秘。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2011-07-14
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    相关资源
    最近更新 更多