开发者

what's the alternative to nested classes in Python

I read a post stating that 'nested classes wasn't pythonic' what's the alternative

please forgive me, this isn't the best example but it's the basic concept. a nested class for performing a task. I'm basically having to connect to a service in multiple threads.

import threading, imporedlib

class Mother(threading.Thread):
    def __init__(self,val1,val2):
        self.VAL1 = val1
        self.VAL2 = val2
    def connecta开发者_高级运维ndrun():
        for i in range(5):
            Child.run(i)
    class Child:
        def run(self):
            importedlib.runajob(Mother.VAL1, Mother.VAL2)


You want to use composition:

import threading, importedlib

class Child:
    def __init__(self, parent):
        self.parent=parent

    def run(self):
        importedlib.runajob(parent.VAL1, parent.VAL2)



class Mother(threading.Thread):
    def __init__(self,val1,val2):
        self.VAL1 = val1
        self.VAL2 = val2

    def connectandrun():
        c= Child(self)
        for i in range(5):
            c.run(i)

Of course the names "Mother" and "Child" are not really appropriate anymore here, but you get the idea.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜