我目前有一些类foo(),其中包含一些变量,这些变量不仅在foo类的所有实例之间共享,而且还由其他类bar共享.
即
class foo():
__init__(self, a, b):
self.a = a
self.b = b
class bar():
__init__(self, a, b):
self.a = a
self.b = b
Run Code Online (Sandbox Code Playgroud)
一种解决方案是制作a和b类变量,但如何在构造期间干净利落地做到这一点?我可以将两个类放在同一个文件中并让它们引用一些全局变量a和b吗?这是不好的做法吗?
由于您没有提供您的意图或现实情况,我将提供一些共享变量访问的方法.
第一种选择:全球.
a=b=None
class foo():
def __init__(self, _a, _b):
global a, b
a, b = _a, _b
class bar():
def __init__(self, _a, _b):
global a, b
a, b = _a, _b
Run Code Online (Sandbox Code Playgroud)
第二个选项:foo的班级变量
class foo():
a = b = None
def __init__(self, a, b):
foo.a, foo.b = a, b
class bar():
def __init__(self, a, b):
foo.a, foo.b = a, b
Run Code Online (Sandbox Code Playgroud)
第三种选择:继承
class foo():
def __init__(self, a, b):
self.a, self.b = a, b
class bar(foo):
pass
Run Code Online (Sandbox Code Playgroud)
第四种选择:外类
class outer():
a = b = None
class foo():
def __init__(self, a, b):
outer.a, outer.b = a, b
class bar():
def __init__(self, a, b):
outer.a, outer.b = a, b
Run Code Online (Sandbox Code Playgroud)
第五种选择:compsition
class foo():
def __init__(self, a, b):
self.a, self.b = a, b
class bar():
def __init__(self, a, b):
self.foo = foo(a,b)
Run Code Online (Sandbox Code Playgroud)
第6个选项:关闭外部函数局部变量
def outer():
a = b = None
class foo():
def __init__(self, _a, _b):
nonlocal a, b
a, b = _a, _b
class bar():
def __init__(self, _a, _b):
nonlocal a, b
a, b = _a, _b
... #things with foo and bar
Run Code Online (Sandbox Code Playgroud)
第7个选项:关闭foo的__init__局部变量.
class foo():
def __init__(self, a, b):
self.a, self.b = a, b
class bar():
nonlocal a, b
#do things with a and b directly
self.bar = bar()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
692 次 |
| 最近记录: |