[英]Python Calling one method of a class having single instance from another class's method
I am new to using python and not sure how can I call one method of a class (another_functionality from class Service) whose instance has to be created only once during a workflow from another class (ServiceCalculator), if I use self.another_functionality(param1 ,param2) 它抛出错误,我不能创建另一个 class 服务实例,因为要求是只使用一个实例。
-----------------------
MainProcess.py
------------------------
Creating Service() object
------------------------
class Service:
def __init__(self):
self.service_cal = ServiceCalculator()
self.service_producer = ServiceProducer()
def process_calling(self, param1, param2):
self.service_cal.process_service(param1, param2)
def another_functionality(self, a, b):
// Another functionality
self.service_producer.send()
class ServiceCalculator:
def process_service(self, param1, param2):
if(param1=True):
self.another_functionality(param1,param2)
您正在寻找的是 singleton 模式。 无论您调用多少次,class 始终只有一个实例。
class Singleton(object):
def __new__(cls, *args, **kwds):
it = cls.__dict__.get("__it__")
if it is not None:
return it
cls.__it__ = it = object.__new__(cls)
it.init(*args, **kwds)
return it
def init(self, *args, **kwds):
pass
https://www.python.org/download/releases/2.2/descrintro/#__new_
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.