Akash
Akash

Reputation: 295

Possible to do this in Python?

I am fairly new to Python, and am not sure if this can be done. As you can see, I couldn't even figure out a good title for the question. Say I have 2 classes,

class A:
    self.B = None

class B:
    def c(self):
        pass

    def d(self):
        pass

Now if I make an instance of the class,

a = A()
a.b = B()

I want something like,

print a.c()

And this should internally call:

a.b.c()

Upvotes: 1

Views: 123

Answers (3)

dgrant
dgrant

Reputation: 1427

class A:
    self.B = None

This won't compile. What does self refer to? Perhaps you meant the following?

class A:
    def __init__(self):
        self.b = None

a = A()
a.b = B()

As @Ignacio said, use getattr or make A inherit from B as follows:

class A(B):
    ...

Upvotes: 1

Patrick87
Patrick87

Reputation: 28302

Why would you want it to work like that? Have A inherit from B if it is going to be understood as having B's methods.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798616

Have A.__getattr__() catch the access to a.c and have it return a.b.c instead.

Upvotes: 2

Related Questions