Вопрос

i read a lot but still can't figure out how to pass a child variable to the parent class:

class anyIF_traffic(object):
    def __init__(self, logpath, typeOfTraffic='cha', name='mytest', port='6060'):
        try:
            assert port in [None, '6060', '6161', '6389', '6636']
            print "PORT: %s"%(port)
            self.port = port
        except AssertionError, msg:
            print "Exception"
            sys.exit (1)
    def __str__(self):
        return self.port

class a_traffic(anyIF_traffic):
    def _init__(self, *args, **kwargs):
        self.port = '6161'
        anyIF_traffic.__init__(self, *args, **kwargs)

class b_traffic(anyIF_traffic):
    def _init__(self, *args, **kwargs):
        self.port = '6389'
        anyIF_traffic.__init__(self, *args, **kwargs)

port = a_traffic(logpath='c://')
print "A. %s"%(port)

port = a_traffic(logpath='c://')
print "B. %s"%(port)

OUT: 
A. 6060

OUT: 
B. 6060

What i would like to get is:

OUT: 
A. 6161

OUT: 
B. 6389

But when i run it i will always get the default value of '6060' since this is declared in the parent class _init.

Of course i could do:

port = a_traffic(logpath='c://', port='6161')
print "A. %s"%(port)

OUT: 
A. 6161

But i am trying to have as much as possible less parameters for the user to take care off.

I know my problem is that i haven't fully understand pythons inheritance of classes and still new in python.

Thanks in adv.

Это было полезно?

Решение 3

If you are interested in strictly adhering to the inheritance paradigm, simply pass port 6161 into the super class constructor:

class a_traffic(anyIF_traffic):
    def __init__(self, *args, **kwargs):
        if len(args) == 5:
            args[4] = '6161'
        else:
            kwargs['port'] = '6161'
        super(a_traffic, self).__init__(*args, **kwargs)

Другие советы

The problem is that you initialized the parent, including the default port 6060, after assigning the override in the child class. Just initialize the parent first:

class a_traffic(anyIF_traffic):
    def _init__(self, *args, **kwargs):
        anyIF_traffic.__init__(self, *args, **kwargs)
        self.port = '6161'

Sometimes its useful to do some pre-setup before calling the parent init, but the other 99% of the time, initialize the parent first.

If you want port to have a different default in the child class, you can simply manipulate the keyword argument dictionary before you pass it along to the parent class:

class a_traffic(anyIF_traffic):
    def _init__(self, *args, **kwargs):
        if len(args) < 4 and "port" not in kwargs:
            kwargs["port"] = "6161"
        anyIF_traffic.__init__(*args, **kwargs)

This allows there to be only one place where self.port gets assigned, so you don't need to worry about whether the child class is overwriting the value set by the parent class, or vise versa.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top