1

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.

Soumen
  • 1,068
  • 1
  • 12
  • 18
  • You already understand the principles of inheritance, since you know that the parent's `__rdiv__()` method is called if the subclass doesn't define one. What makes you think it is any different for `__init__()`? – Daniel Roseman Sep 11 '15 at 11:40
  • Thanks for the reply. Actually, I knew that __init__ of parent has to be called from child's __init__ (if it has any). So, I thought may be in this case also, parent's __init__ has to be called. – Soumen Sep 11 '15 at 11:46
  • @Soumen parent's `__init__()` has to be specifically called from child's init only if the child has an `__init__()` itself. If the child does not have the `__init__()` it uses the `__init__()` from its parent. When you inherit a class in python, you inherit all of its attributes and functions, which also includes functions like init, etc. – Anand S Kumar Sep 11 '15 at 11:52

1 Answers1

2

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

Community
  • 1
  • 1
Lawrence Benson
  • 1,398
  • 1
  • 16
  • 33