简体   繁体   中英

Creating an instance of a class from a function in another class



I'm having trouble figuring out how to create an instance of an object from another class .

Below I've given an example, where we have a MainWindow class that represents eg a web browser. Then, there is another class called MainWindowTab .

MainWindow is initialized with one tab, called "tab1", but I want to be able to add another tab and call it "tab2" (and then add "tab3", and "tab4" etc), but I'm having problem with naming it as you can see below.

Also, any tips relating to a destructor for the tab objects would be nice if it's not as straightforward as it would seem.

Any help would be great, thanks

Code

class MainWindow(object):

    def __init__(self):
        self.tab = MainWindowTab(0)
        self.tabList = [self.tab]

    def addTab(self, num):
        newName = "tab"+str(len(self.tabList)+1)
        # How to add a new Tab with this name? Below will simply name the new tab as literally 'newName'
        # self.newName = MainWindowTab(10)


class MainWindowTab(object):

    def __init__(self, num):
        self.posn = num

You can make your tab instance variable a list , and then append more objects to it

class MainWindow(object):
    
    def __init__(self, numberOfTabs):
        self.tab = [MainWindow() for _ in range(numberOfTabs)]
        self.tabList = [self.tab]

    def addTab(self, num):
        newName = "tab"+str(len(self.tabList)+1)
        # How to add a new Tab with this name? Below will simply name the new tab as literally 'newName'
        # self.newName = MainWindowTab(10)
        self.tab.append(MainWindowTab(num))


class MainWindowTab(object):

    def __init__(self, num):
        self.posn = num

The most obvious way is to use setattr:

def addTab(self, num):
    newName = "tab"+str(len(self.tabList)+1)
    setattr(self, newName, MainWindowTab(10))

But as stated in another answer, a better way for sequences data is to use lists.

You probably don't want to assign each tab to a new attribute on self , just use the list you've already created and access them from there. Also, you don't need (object) in class definitions anymore in Python 3.

class MainWindow:
    def __init__(self):
        self.tablist = [MainWindowTab(0)]

    def add_tab(self):
        tab_num = len(self.tablist)
        self.tablist.append(MainWindowTab(tab_num)

Now each tab will be accessible as self.tablist[0] , self.tablist[1] , etc.

For destroying tabs, you'll want to remove them from the main list as well as call whatever destructor method is required on the object itself. Something like:

    def kill_tab(self, num):
        """Kill tab number 'num'"""
        try:
            tab = self.tablist.pop(num)
            tab.destroy()
        except IndexError:
            print(f"Tab {num} doesn't exist!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM