tags:

views:

47

answers:

2

Hi.

I have two classes, suppose A and B. Within B, I instantiate A.

I have a function func() that is required by both the classes.

How should I go about it? I had thought of this approach:

class A:
   func()

class B:
   x = A()
   func()

def func():

And then I can access func() from within A or B. Is this approach OK or is there a better way to do this (perhaps using an OO approach)

Note that I am new to OO programming and that is why I am interested in knowing whether I can apply any OO design to this.

Edit: The function can differ in the arguments it takes.

+1  A: 

Define func before you define either class, and it will be available to both.

Alex Bliskovsky
@Alex: Is this is a good practice as such? Or this is a result of poor design.
Chris
As far as I know, this is the simplest way of doing it, and as the Zen of Python states, ``Simple is better than complex.``
Alex Bliskovsky
@Chris: Could be good, could be bad. It depends on what func is and what the classes are. In Python, module-level functions like this are not illegal like they are in Java (though I should note that Java folks have several patterns that work around this), and module-level functions do get used quite a bit in the standard Python libraries, for example.
Owen S.
Generally, it's good. Module-level functions are standard practice in Python.
katrielalex
Functions that are generic and don't require to be bound to a class are great for being globally available in the module, moreso if it has potential uses outside of the scope of it's own module (parts of your application using the code from the module can also find use for it)
kRON
A: 

func here can me a method of common base class

class Base(object):
    def func():
        #...
class A(Base):
    #...
class B(Base):
    #...
Odomontois