3

Is it OK to define functions outside a particular class, use them in the class, and then import that class elsewhere and use it?

Are there any risks associated with doing that, rather than making all functions methods of the class?

I'm writing this code in python 2.7

For example, make a class like this:

def func(a):
    return a

class MyClass():

    def class_func(self, thing):
        return func(thing)

Then import MyClass into another python script and use its class_func method.

Charon
  • 2,344
  • 6
  • 25
  • 44
  • 2
    Suppose you are using some library in your class - it will look like so. BTW, method definition should have a reference to instance as 1st argument: `def class_func(self, thing): ` – Eugene Lisitsky Mar 16 '16 at 10:54
  • Good point, thanks. I've edited my answer. – Charon Mar 16 '16 at 10:55

2 Answers2

1

It's ok, but if func uses only in MyClass it can be helpful to make it staticmethod and place inside MyClass near class_func:

class MyClass(object):
    @staticmethod
    def _func(a):
        return a

    def class_func(self, thing):
        return type(self)._func(thing)
Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159
1

Doing this is okay, and in fact a language feature of python. Functions have access to names of the scope they are defined in, regardless of where they are called from.

For example, you can also do something like this:

factor = 2
def multiply(num):
    return num*factor

See this post for some background information.


The "risk" associated with this is that the outside name is explicitly not under your control. It can be freely modified by other parts of your program, without the implication being clear.

Consider this example:

def func(a):
  return a

class MyClass(object): # note: you should inherit from object in py2.X!
  def class_func(self, thing):
    return func(thing)

myinstance = MyClass()
foo = myinstance.class_func(1)

def func(a):
  return str(a)

bar = myinstance.class_func(1)

Here, foo and bar will be different, namely the integer 1 and the string "1".

Usually, making this possible is the entire point of using such a structure, however.

Community
  • 1
  • 1
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119