Class initialization without __init__ method

回眸只為那壹抹淺笑 提交于 2019-12-24 11:37:36

问题


While going through scapy source code (https://github.com/jwiegley/scapy), I came across the fact none of the Ether, IP, TCP, UDP or any other protocol classes contain any __init__ method, nor they have any class methods with @classmothod annotation. All of this classes inherit the Packet class, which by the way contains __init__ method.

Code structure is like this :

class Ether(Packet):
    # class methods

class IP(Packet, IPTools):
    # class methods

# Other protocol classes

So, I am wondering how instances of this classes are created when we create a packet like this :

packet = Ether()/IP()/TCP()

I could understand the "/" notation. The Packet class has overridden the __rdiv__() method, and as all these classes are subclasses of Packet, __rdiv__() of their parent Packet instance is called.

But, how the instances of these classes are being created is still unclear to me.

Also, IP class can be created like this

ip = IP(src="10.0.0.1")

As, IP doesn't have any __init__ method, how this initialization is possible?

For reference, __init__ of Packet class looks like this :

def __init__(self, _pkt="", post_transform=None, _internal=0, _underlayer=None, **fields):
    # initialization code

Any help will be appreciated.


回答1:


if the class doesnt contain a own __init__() it will just take the one from the superclass. a overwritten __init__() is only requiered, when adding changes. maybe this will help you understand



来源:https://stackoverflow.com/questions/32522565/class-initialization-without-init-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!