Mike Pennington
Mike Pennington

Reputation: 43097

Chained Python class invocations

I am trying to build a set of classes to define hierarchical properties for protocols in the OSI stack... in an abstract sense, I just need to inherit properties from parent python classes, but I need to be able to invoke the entire class chain at once... so, I'm looking for something like this...

#!/usr/bin/env python

class Foo(object):
    def __init__(self,fooprop1=None):
        return None
class Bar(Foo):
    def __init__(self,barprop1=None):
        return None

if __name__=='__main__':
    tryit = Foo(fooprop1="someMacAddress").Bar(barprop1="someIpAddress")

However, invoking that script complains that AttributeError: 'Foo' object has no attribute 'Bar'

Can someone show me a way to get this done in python? Thanks in advance...

Upvotes: 1

Views: 507

Answers (2)

jfs
jfs

Reputation: 414905

Take a look how it is done in scapy:

$ sudo scapy
Welcome to Scapy (2.1.0) 
>>> sr(IP(dst="8.8.8.8") / UDP() / DNS(rd=1,qd=DNSQR(qname="stackoverflow.com")))
Begin emission:
..............................Finished to send 1 packets.
.............*
Received 44 packets, got 1 answers, remaining 0 packets
(<Results: TCP:0 UDP:1 ICMP:0 Other:0>, <Unanswered: TCP:0 UDP:0 ICMP:0 Other:0>)
>>> ans = _[0]
>>> ans.summary()
IP / UDP / DNS Qry "stackoverflow.com"  ==> IP / UDP / DNS Ans "64.34.119.12"

scapy uses / operator to compose a packet from different layers.

Upvotes: 2

Apalala
Apalala

Reputation: 9244

As S.Lott mentions, you should be doing something like:

class Foo(object):
    def __init__(self,fooprop1=None):
        return None

class Bar(object):
    def __init__(self,barprop1=None, afoo):
        self.foo = afoo
        return None

if __name__=='__main__':
    thefoo = Foo(fooprop1="someMacAddress")
    thebar = Bar(barprop1="someIpAddress", thefoo)

Upvotes: 1

Related Questions