Here you can use class inheritance . Inheritance allows you to create an object based on another object, inheriting all its functions and attributes.
In this case, it looks like this:
class A(object): def foo(self): print "blah" class B(A):
After this announcement
>>> B().foo() "blah"
This works because:
- You created class
A and created the foo method for it. - You created a class
B that inherits from A , which means that when A "gave birth to it," B born with everything that A .- In our case,
B is an exact copy of A , since we did not do anything with it. However, we could make changes or add other methods.
Example:
class A(object): def foo(self): print "blah" class B(A): def newfoo(self): print "class A can't do this!"
In this case, we will see:
>>> A().foo() blah >>> B().foo() blah >>> A().newfoo() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'A' object has no attribute 'newfoo' >>> B().newfoo() class A can't do this!
In particular, the reason your code above did not work is because when you tried to install B.foo , you wrote
class B(object): foo = A.foo
instead
class B(object): foo = A().foo
When you wrote A.foo without () , you requested a method directly from type A that would not work in Python. If you need to execute foo = A().foo , then you must create an instance of object A , then get a copy of your foo method and then assign it.
source share