Last active
June 25, 2019 15:17
-
-
Save HoweChen/8df0dfb6e914e9f2db5436f051d013e8 to your computer and use it in GitHub Desktop.
[多进程共享嵌套class] #Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from multiprocessing.managers import BaseManager, NamespaceProxy | |
| class TestClass(object): | |
| def __init__(self, a): | |
| self.a = a | |
| def b(self): | |
| print self.a | |
| class MyManager(BaseManager): pass | |
| class TestProxy(NamespaceProxy): | |
| # We need to expose the same __dunder__ methods as NamespaceProxy, | |
| # in addition to the b method. | |
| _exposed_ = ('__getattribute__', '__setattr__', '__delattr__', 'b') | |
| def b(self): | |
| callmethod = object.__getattribute__(self, '_callmethod') | |
| return callmethod('b') | |
| MyManager.register('test', TestClass, TestProxy) | |
| if __name__ == '__main__': | |
| manager = MyManager() | |
| manager.start() | |
| t = TestClass(1) | |
| print t.a | |
| mt = manager.test(2) | |
| print mt.a | |
| mt.a = 5 | |
| mt.b() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from multiprocessing.managers import SyncManager | |
| class PointClass: | |
| def __init__(self, value): | |
| self.value = value | |
| class MathsClass: | |
| def __init__(self, point_one, point_two): | |
| self.point_one = PointClass(point_one) | |
| self.point_two = PointClass(point_two) | |
| def get_point_one(self): | |
| # 这里需要一个获取成员变量的函数才能正常访问,因为SyncManager返回的proxy默认不带有 | |
| # __getattribute__, __setattr__ 和 __delattr__ 属性 | |
| # 有一种办法是以一个继承的proxy来register这个类 | |
| return self.point_one | |
| def add(self): | |
| result = self.point_one.value + self.point_two.value | |
| print(result) | |
| return result | |
| def mul(self, x, y): | |
| return x * y | |
| class MyManager(SyncManager): | |
| pass | |
| MyManager.register('Maths', MathsClass) | |
| # MyManager.register("Point", PointClass) | |
| if __name__ == '__main__': | |
| # four = PointClass(4) | |
| # three = PointClass(3) | |
| with MyManager() as manager: | |
| maths = manager.Maths(3, 4) | |
| print(maths.get_point_one().value) | |
| # print(maths.add(four, three)) # prints 7 | |
| print(maths.add()) | |
| print(maths.mul(7, 8)) # prints 56 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment