how to return a function in a different class in python 3.3 -
i know bad description how can work:
class test1(): def test_p1(): print("this part 1 of test1") def test2(): return test_p1()
thanks in advance!
well, there several options.
the basic are:
create instance first
class test1(): def test_p1(self): print("this part 1 of test1") def test2(): return test1().test_p1()
however, should use when having new instance makes sense (depends on api).
make class method
class test1(): @classmethod def test_p1(cls): print("this part 1 of test1") def test2(): return test1.test_p1()
make static method (discouraged)
class test1(): @staticmethod def test_p1(): print("this part 1 of test1") def test2(): return test1.test_p1()
alternative: use inheritance
in cases (maybe case too, not know) makes sense utilize inheritance: create class inherit test1
. way can override parts of , refer parent methods. example:
class test1(): def test_p1(self): print("this part 1 of test1") class someotherclass(test1): def test2(self): return super(someotherclass, self).test_p1()
and use this:
my_instance = someotherclass() result = my_instance.test2()
but again, depends on api / library.
alternative 2: module-level function
user @user2357112 correctly pointed out, module-level function can better (simpler) idea:
def test_p1(): print("this part 1 of test1") def test2(): return test_p1()
side note: pep8
to avoid confusion, python dynamic, should give "hint" developers on using, , in general follow coding style defined in pep8:
- module names
all_lower_case
, - functions , methods
all_lower_case
, - classes
camelcase
(same applies factory-like functions returning class instances), - constants
all_upper_case
, - object properies
all_lower_case
,
(and many more - above non-confusing naming)
Comments
Post a Comment