将另一个文件中的函数嵌入Python类
我有一些将另一个文件中的函数嵌入Python类,python,class,Python,Class,我有一些commonfunctions,可以作为不同类的方法重用。我将这些函数存储在模块目录中的commonfunctions.py文件中。我希望将函数嵌入到我需要的类中,并能够修改类的属性。我做了一些尝试,但没有一个是切实可行的。我想知道做这件事最好的方法是什么 commonfunctions.py def mycommonfun(self,myarg): self.target = myarg+3 class mydummyclass(object): def mycomm
commonfunctions
,可以作为不同类的方法重用。我将这些函数存储在模块目录中的commonfunctions.py文件中。我希望将函数嵌入到我需要的类中,并能够修改类的属性。我做了一些尝试,但没有一个是切实可行的。我想知道做这件事最好的方法是什么
commonfunctions.py
def mycommonfun(self,myarg):
self.target = myarg+3
class mydummyclass(object):
def mycommonfun(self,myarg):
self.target = myarg+3
mainfile.py
import commonfunctions
class A(anotherclass):
def __init__(self):
self.target = None
# not working
commonfunctions.mycommonfun
class B(anotherclass):
def __init__(self):
self.target = None
# I can't modify self.target
self.mycommonfun = commonfunctions.mycommonfun
class C(anotherclass):
# it works but it hides all the docstring
def mycommonfun(self,myarg):
commonfunctions.mycommonfun(self,myarg)
class D(anotherclas,commonfunctions.mydummyclass):
pass #it works not sure why I have problem with hinting of the arguments
from commonfunction import ParentClass
class ChildClass(ParentClass):
def __init__(self, target):
super().__init__(target)
child = ChildClass(5) # self.target = 5
child.some_function(5) # self.target = 3 + 5 = 8
您需要做的是继承其他类方法 commonfunction.py
class ParentClass:
def __init__(self, target):
self.target = target
def some_function(self, n):
self.target = 3 + n
mainfile.py
import commonfunctions
class A(anotherclass):
def __init__(self):
self.target = None
# not working
commonfunctions.mycommonfun
class B(anotherclass):
def __init__(self):
self.target = None
# I can't modify self.target
self.mycommonfun = commonfunctions.mycommonfun
class C(anotherclass):
# it works but it hides all the docstring
def mycommonfun(self,myarg):
commonfunctions.mycommonfun(self,myarg)
class D(anotherclas,commonfunctions.mydummyclass):
pass #it works not sure why I have problem with hinting of the arguments
from commonfunction import ParentClass
class ChildClass(ParentClass):
def __init__(self, target):
super().__init__(target)
child = ChildClass(5) # self.target = 5
child.some_function(5) # self.target = 3 + 5 = 8