Reputation: 4958
I really didn't know what title I should choose. Anyway, I have code like this (this is fixtures):
from fixture import DataSet
class CategoryData(DataSet):
class cat1:
name = 'Category 1'
class cat2:
name = 'Category 2'
parent = cat1
The problem is I can't reference cat1 in cat2 like that:
File "/home/julas/cgp/cgp/datasets/__init__.py", line 11, in cat2
parent = cat1
NameError: name 'cat1' is not defined
How can I do it?
Upvotes: 1
Views: 268
Reputation: 57474
There are two problems here.
First, Python doesn't do nested scoping like that for you. To access CategoryData.cat1
, you need to spell it out.
Second, and a bigger issue, is that there's no way to access CategoryData
from there: the class hasn't been defined yet, since you're in the middle of defining it. If you do this:
class Object(object):
a = 1
b = Object.a
it'll fail, because the value of Object
isn't assigned until the end of the class definition. You can think of it as happening like this:
class _unnamed_class(object):
a = 1
b = Object.a
Object = _unnamed_class
There's no way to reference a
from where b
is assigned, because the containing class hasn't yet been assigned its name.
In order to assign parent
as a class property, you need to assign it after the containing class actually exists:
class CategoryData(DataSet):
class cat1:
name = 'Category 1'
class cat2:
name = 'Category 2'
CategoryData.cat2.parent = CategoryData.cat1
Upvotes: 3
Reputation: 5599
You either: Move it out of the definition:
CategoryData.cat2.parent=CategoryData.cat1
Or, if it's an object attribute (and not a class attribute):
class cat2:
name = 'Category 2'
def __init__(self):
self.parent = cat1
Upvotes: 1