Class initialization without __init__ method

2019-08-04 10: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.

标签: python class
1条回答
我命由我不由天
2楼-- · 2019-08-04 11:18

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

查看更多
登录 后发表回答