首页 > 解决方案 > 无参数实例化

问题描述

所以我试图使用另一个类的方法,但我必须使用方法从类中添加所有参数。有没有办法解决?

class MainPage(tk.Frame):

    def __init__(self, parent, controller):
       tk.Frame.__init__(self, parent)
       label = tk.Label(self, text = "aaaa")
       label.pack(pady = 10, padx = 10)

       A = managers()
       method = getattr(A, printAll) ## "printAll" is the method im trying to get 

       addemployee = tk.Button(self, text = "Start", command = method)
       addemployee.pack(pady = 10, padx = 10)



class managers(workers):

    def __init__(self, firstname, surname, age, postcode, wage, Employees = None):
        super().__init__(firstname, surname, age, postcode, wage)

    def printAll(self): #### the method i want to use
        for emp in self.employees:
            print(emp.Fullname(), "-", emp.Age(), "-", self.Postcode(), "-", self.Wage())

标签: pythonpython-3.xinstance

解决方案


您可以使用默认值,因此您不必传递所有内容。

class managers(workers):

def __init__(self, firstname="fname", surname="sname", age="196", postcode="pc", wage="1$", Employees = None):

如this SO answer中所建议的,另一个允许您完全自由的选项是使用 args 和关键字 args 传递参数def __init__(self, *args, **kwargs):


推荐阅读