how can I solve this problem simply and clearly

dieter dieter at handshake.de
Fri Nov 9 01:58:33 EST 2018


lampahome <pahome.chen at mirlab.org> writes:
> I have two categories A,B, and A has 2 items A1,A2, and B have 2 items B1,
> B2.
>
> I have two class A and B, and A will handle A1,A2, B handle B1,B2.
>
> I want to parse one of A1,A2,B1,B2 to script and generate the corresponding
> class(object).
>
> Ex: Both in class A and B, all have func1(), func2().
> What I thought to design is below:
> -------------------------------------------------
> ...
> def get_class(obj):
>     if obj == 'A1' or obj == 'A2':
>         return A(obj)
>      else:
>         return B(obj)
>
> # A = get_class(A1)

Try `A = get_class('A1')` (instead of `A = get_class(A1)`).

In Python, you must carefully distinquish between a name (such as
`A1`) and a string (such as `'A1'`). A name is used to refer
to something, previously "bound" to the name (e.g. via an assignment).
If you use a name not yet bound (like in your `get_class(A1)`),
you will get a `NameError`.




More information about the Python-list mailing list