[Tutor] Inner Class access to outer class attributes?
stv
stvsmth at gmail.com
Thu Mar 23 21:17:31 CET 2006
# So I figure out inner classes while typing the
# first draft of this email, at least mostly
# How do I access the "outer" class attributes from
# the inner class?
class GroupLocation(list): ### Note subclass of list
class _Sublocation(object):
def __init__(self, sublocation, action):
self.sublocation = sublocation
self.action = action
def do_stuff(self):
###
### How would I get to GroupLocation attributes?
###
print GroupLocation.name, self.sublocation
def __init__(self, name, group_location):
self.name = name
self.group_location = group_location
def add_sublocation(self, sublocation, action):
self.append(GroupLocation._Sublocation(sublocation, action)
group = GroupLocation('group1name', 'group1location')
group.add_sublocation('sublocation1','foo')
group.add_sublocation('sublocation2','bar')
group.add_sublocation('sublocation3','zip')
group.add_sublocation('sublocation4','foo')
[sub.do_stuff() for sub in group if sub.action == 'foo']
# output (if it worked):
# Group1location sublocation1
# Group1location sublocation4
#
# instead I get this:
# AttributeError: type object 'GroupLocation' has no attribute 'name'
# Now, I suppose I could start down this road:
class GroupLocation(object):
def __init__(self,name, group_location):
self.name = name
self.group_location = group_location
self.sublocations = []
def add_sublocation(self,sublocation, action):
self.sublocations.append((sublocation, action))
group = GroupLocation('group1', 'group1location')
group.add_sublocation('sublocation1','foo')
group.add_sublocation('sublocation2','bar')
group.add_sublocation('sublocation3','zip')
group.add_sublocation('sublocation4','foo')
for sub in group.sublocations:
if sub[1] == 'foo':
print group.group_location, sub[0]
# output:
# Group1location sublocation1
# Group1location sublocation4
# But that feels wrong in several ways:
# 1) Any time I want to do_stuff() I have
# to retype
# 2) sub[1] & sub [0] are confusing after
# not reading the code for a few hours.
More information about the Tutor
mailing list