简体   繁体   English

了解继承并将子变量传递给父类

[英]Understanding inheritance and passing child variable to the parent class

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 . 但是当我运行它时,我将始终获得默认值'6060',因为这是在父类_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. 我知道我的问题是我还没有完全理解类的pythons继承,而且在python中仍然是新的。

Thanks in adv. 谢谢你。

The problem is that you initialized the parent, including the default port 6060, after assigning the override in the child class. 问题是您在子类中分配覆盖后初始化父级,包括默认端口6060。 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. 有时在调用父init之前进行一些预先设置是有用的,但在其他99%的时间,首先初始化父级。

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: 如果您希望port在子类中具有不同的默认值,则可以在将关键字参数字典传递给父类之前简单地操作它:

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. 这允许只有一个地方可以分配self.port ,因此您不必担心子类是否覆盖父类设置的值,反之亦然。

If you are interested in strictly adhering to the inheritance paradigm, simply pass port 6161 into the super class constructor: 如果您对严格遵守继承范例感兴趣,只需将端口6161传递给超类构造函数:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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