Reputation: 1642
I am trying to save me from repeating code in two classes, I have tested the following snippet and it works, I am wondering if it is a good practice or should I consider using inheritance. In that case is there something particularly wrong about this approach?
def do_something_with_self(obj):
print 'Hello, I was called from %s' % obj.name
class A(object):
name = "Class A"
def do_something(self):
do_something_with_self(self)
class B(object):
name = "Class B"
def do_something(self):
do_something_with_self(self)
if __name__ == '__main__':
a = A()
b = B()
a.do_something()
b.do_something()
Upvotes: 3
Views: 83
Reputation: 49318
It is a good practice if the situation calls for it. Sometimes an object needs to be passed to a function that works with objects of that type without being a method of that type of object, and that's the way to do it. For example, your object might have a logging function that includes a dir()
of the object - dir(self)
would be the way to do that.
However, if A
and B
are really both objects of the same overarching kind (like Letter
), I would recommend using inheritance.
Upvotes: 3
Reputation: 49826
This is good practice. In general, you should avoid inheritance when you have a choice between inheritance and another simple mechanism for code sharing.
Upvotes: 3