Python 如何在另一个类中使用模块的方法
我有一个名为mymodule的模块。 模块有一个方法Python 如何在另一个类中使用模块的方法,python,python-3.x,Python,Python 3.x,我有一个名为mymodule的模块。 模块有一个方法sayHello() 所以这是可行的: import mymodule print(mymodule.sayHello()) 现在我想对一个类使用mymodule中的方法(所有方法) import mymodule class Grandma(object): def __init__(self): ##import methods from mymodule. 所以我可以在另一节课上做: from grandm
sayHello()
所以这是可行的:
import mymodule
print(mymodule.sayHello())
现在我想对一个类使用mymodule
中的方法(所有方法)
import mymodule
class Grandma(object):
def __init__(self):
##import methods from mymodule.
所以我可以在另一节课上做:
from grandma import Grandma
self.Grandma.sayHello()
如何在python中实现这一点
atm我只能通过使用我不想要的额外属性来实现这一点您可以直接在类定义中导入内容:
class Something:
from stuff import a, b
def __init__(self):
self.a()
您可能想看看如何在实际项目中使用它。我并不是说这是最好的方法(实际上我觉得它比较难看),但它很好用。我认为这是一个比较糟糕的设计,建议你找到一种不同的表达方式 也就是说,使用父类的方法使这变得非常简单:我们只需循环遍历模块的目录,并将所有属性分配给类上相同的属性
from abc import ABC
class ModuleABC(ABC):
def __init_subclass__(cls, module, **kwargs):
super().__init_subclass__(**kwargs)
for name in dir(module):
# Ignore attributes we define as part of the class and "private" attributes
if not hasattr(cls, name) and not name.startswith('_'):
setattr(cls, name, getattr(module, name))
import math
class Grandma(ModuleABC, module=math):
pass
print(Grandma.tau)
# 6.283185307179586
实际上,这并不要求
module
是一个模块:它应该适用于几乎任何目标。为什么要这样做?任何可以访问Grandma
类的人也可以访问mymodule
并直接调用那里的函数。在self.Grandma.sayHello()
中的self
是什么?我怀疑它一定是:来自mymodule import Grandma
,因为Grandma类是在mymodule.py中定义的。然后你可以做:grandma=grandma()
然后grandma.sayHello()