Reputation: 553
If I have two classes, and one of them has a function that I want to use in my other class, what do I use so that I don't have to rewrite my function?
Upvotes: 47
Views: 73563
Reputation: 95449
There are several approaches:
The following examples use each for sharing a function that prints a member.
Inheritance
class Common(object):
def __init__(self,x):
self.x = x
def sharedMethod(self):
print self.x
class Alpha(Common):
def __init__(self):
Common.__init__(self,"Alpha")
class Bravo(Common):
def __init__(self):
Common.__init__(self,"Bravo")
Delegation
class Common(object):
def __init__(self,x):
self.x = x
def sharedMethod(self):
print self.x
class Alpha(object):
def __init__(self):
self.common = Common("Alpha")
def sharedMethod(self):
self.common.sharedMethod()
class Bravo(object):
def __init__(self):
self.common = Common("Bravo")
def sharedMethod(self):
self.common.sharedMethod()
Super-sneaky Delegation
This solution is based off of the fact that there is nothing special about Python member functions; you can use any function or callable object so long as the first parameter is interpreted as the instance of the class.
def commonPrint(self):
print self.x
class Alpha(object):
def __init__(self):
self.x = "Alpha"
sharedMethod = commonPrint
class Bravo(object):
def __init__(self):
self.x = "Bravo"
sharedMethod = commonPrint
Or, a similarly sneaky way of achieving delegation is to use a callable object:
class Printable(object):
def __init__(self,x):
self.x = x
def __call__(self):
print self.x
class Alpha(object):
def __init__(self):
self.sharedMethod = Printable("Alpha")
class Bravo(object):
def __init__(self):
self.sharedMethod = Printable("Bravo")
Upvotes: 31
Reputation: 11863
you create a class from which both classes inherit.
There is multiple inheritance, so if they already have a parent it's not a problem.
class master ():
def stuff (self):
pass
class first (master):
pass
class second (master):
pass
ichi=first()
ni=second()
ichi.stuff()
ni.stuff()
Upvotes: 7
Reputation: 188004
There are two options:
Example:
class A(object):
def a1(self):
""" This is an instance method. """
print "Hello from an instance of A"
@classmethod
def a2(cls):
""" This a classmethod. """
print "Hello from class A"
class B(object):
def b1(self):
print A().a1() # => prints 'Hello from an instance of A'
print A.a2() # => 'Hello from class A'
Or use inheritance, if appropriate:
class A(object):
def a1(self):
print "Hello from Superclass"
class B(A):
pass
B().a1() # => prints 'Hello from Superclass'
Upvotes: 45