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?
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
CategoryDatafrom there: the class hasn’t been defined yet, since you’re in the middle of defining it. If you do this:it’ll fail, because the value of
Objectisn’t assigned until the end of the class definition. You can think of it as happening like this:There’s no way to reference
afrom wherebis assigned, because the containing class hasn’t yet been assigned its name.In order to assign
parentas a class property, you need to assign it after the containing class actually exists: