使用super()继承关键字参数,但在创建实例时未直接列出它们

问题描述 投票:1回答:1

抓住这个我有点麻烦,我觉得很简单,概念。我正在创建一些tkinter应用程序(不相关),我正在通过super和* args,** kwargs继承属性:

class MainApp():

    def __init__(self, master = None, y = 10, x = "sample string"):
        self.master = master  
        self.y = y
        self.x = x
    # master is in the end root = tk.Tk(), 
    # which i pass as argument when creating that object, y and x are just for testing purpose

class Replica(MainApp):
    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)
        print(args)
        print(kw)
    # This is also just for testing how this stuff works, thing is;
    # When I run following code:


root = tk.Tk()
app = Replica(root)
print (app.x, app.y) # this returns ~ sample string 10; as expected
root.mainloop()

#But when output of print(args, kwargs) in Replica class __init__ method,
#it returns only (<tkinter.Tk object .>,) in printing args and empty dic
#{} in kwargs, therefore x and y werent considered either args or kwargs
# WHY?


#Well, but if i initialize Replica like this:

root = tk.Tk()
app = Replica(master = root, y = 5, x = "changed string")
root.mainloop()
# It returns empty tuple for args (), and full kwarg dic like this:
{'master': <tkinter.Tk object .>, 'y': 2, 'x': 'changed string'}

# In same logic, if I initiate Replica like this:


app = Replica(root, 10, "changed string")
# This returns all attributes in args, therefore print(args) in __init__
# method returns (<tkinter.Tk object .>, 10, 'changed string') 
# and kwargs are empty {}

# Similiarly, when running this:
app = Replica(root, 10, x = "changed string")
# It shifts x to kwargs dictionary and return is
# (<tkinter.Tk object .>, 10) and {'x': 'changed string'}

我的意思是我有点理解发生了什么,我不是盲目的,但仍然想知道为什么master,y和x不能立即作为kwargs继承,毕竟,它们是MainApp init方法中的关键字参数。我认为super()方法会处理这个问题。应用程序工作正常,但我有点沮丧,因为不理解这一点,并会欣赏一些见解。

如何在x和y属性继承时...

def __init__(self, *args, **kwargs)
    super().__init__(*args, **kwargs) 

..没有指定x或y。甚至在奔跑时:

def __init__(self, master):
    super().__init__(master)

它运行良好并继承x和y属性..

再一次,我将非常感谢您的一些见解,谢谢。

python class inheritance tkinter kwargs
1个回答
1
投票

这与super或继承无关。它只是在没有传递参数时采用其默认值的参数。这是一个简单的例子:

def foo(x=5):
  print('foo: x =', x)

def bar(*args, **kwargs):
  print('bar:', args, kwargs)
  foo(**kwargs)

bar()
bar(x=2)

输出:

bar: () {}
foo: x = 5
bar: () {'x': 2}
foo: x = 2

Demo

argskwargs是传递给bar的值,最后将相同的值传递给foo。如果没有任何内容传递给bar,则没有任何内容传递给foo,并使用默认值。

super().__init__(*args, **kw)相当于MainApp.__init__(*args, **kw)。默认值不是“继承”,它们只是正常使用。

© www.soinside.com 2019 - 2024. All rights reserved.