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.

3
  • 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__()? Commented Sep 11, 2015 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. Commented Sep 11, 2015 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. Commented Sep 11, 2015 at 11:52

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.