我不确定这种语言是否可行,但想象一下:
class Parent(object):
def __init__(self, number):
self.variable_to_access = "I want this"
self.object_list = []
for i in range(number): self.object_list.append(Object_In_List(i))
class Object_In_List(object):
def __init__(self): pass
def my_method(self):
# How can I access variable_to_access
我已经过度简化了这一点,但我认为Object_In_List
可以继承Parent
,但Parent
将包含许多其他项目,我担心内存使用情况。
我想避免不断传递variable_to_access
本身。这实际上是否可以在variable_to_access
内访问my_method()
?
由于
答案 0 :(得分:2)
这是一个稍微复杂的例子,其行为类似于Java内部类
class Parent(object):
def __init__(self, number):
self.variable_to_access = "I want this"
self.object_list = [] for i in range(number):
# Pass in a reference to the parent class when constructing our "inner class"
self.object_list.append(Object_In_List(self, i))
class Object_In_List(object):
# We need a reference to our parent class
def __init__(self, parent, i):
self.parent = parent
# ... So we can forward attribute lookups on to the parent
def __getattr__(self, name):
return getattr(self.parent, name)
# Now we can treat members of the parent class as if they were our own members (just like Java inner classes)
def my_method(self):
# You probably want to do something other than print here
print(self.variable_to_access)
答案 1 :(得分:1)
class Parent(object):
def __init__(self, number):
self.variable_to_access = "I want this"
self.object_list = []
for i in range(number):
self.object_list.append(Object_In_List(self.variable_to_access, i))
class Object_In_List(object):
def __init__(self, parent_var, i):
self.pv = parent_var
def my_method(self):
# How can I access variable_to_access
# self.pv is what you want
答案 2 :(得分:0)
现在似乎唯一存在Object_In_List
个Parent
对象的地方属于self.object_list
属性Parent
。如果是这种情况,那么当您访问Object_In_List
时,您就在my_method
班级,因此您甚至不需要Object_In_List
中的Parent
。如果这些对象存在于该列表之外,则无论如何都必须传递Parent
对象或变量,如其他答案所示。
如果您想要有创意,可以使用{{1}}的类属性。这不会是“变量”,除非你的class属性是一个字典,但是那里有内存。