In C we can easily define methods outside of class:
struct X {
int a, b ;
// member function declaration only
int add();
};
// define member function outside its class declaration
int X::add() { return a b; }
I want to do the same thing (or something like this in python) but I don't know how
I saw some solutions to similar problems but they included creating some new functions like this:
def my_func(self_class, arg):
# do something with arg
return something
class MyClass:
function = my_func
Is it possible to define method outside of class without creating unnecessary functions?
CodePudding user response:
The lambda way
You example can be done with lambda
and =
:
class X:
pass
X.add = lambda s: s.a s.b
The def way
The def
keyword won't allow you to assign directly to a class, but you can make a function, assign it, and then delete it. While this isn't what you were hoping for, it is likely the best you can do:
class X:
pass
def add(s):
return s.a s.b
X.add = add
del add
CodePudding user response:
Guess I am not sure what you're trying to avoid unless you have functions you want to use in many classes. In that case I would make a base class and inherit it.
As for your second example, calling an external function means you need to explicitly pass "self" since the instance won't do that for you. Another reason I prefer inheritance.
The example is very basic so I am not sure what you wish to achieve. For example add can be built into the class using an overload of __add__
. I do that with classes for Vectors.
CodePudding user response:
Python doesn't allow you to define functions in a namespace for another. You can only assign functions to class after defining them. If you want to avoid manual assignment, you can define a simple decorator to help you:
def methodof(tp):
def setter(func):
setattr(tp, func.__name__, func)
return func
return setter
Test:
>>> class Foo:
... pass
...
>>> @methodof(Foo)
... def hello(self):
... print('hello')
...
>>> Foo().hello()
hello