The problem of failure to create class attributes using [list generation] in Python

encountered a strange problem when creating a class. The main reason is that the prompt refers to a variable that does not exist. The following is explained by specific code.

class Stu_A(object):
    name="student{}"
    other_name=name.format("A")
    def __init__(self):
        pass
a=Stu_A()
print(a.other_name)

the above code works correctly, but if you add another class attribute (which is a list generated by the previous property formatting), it will prompt for an error that the variable is not defined. The code is as follows:

class Stu_B(object):
    name="student{}"
    other_name=name.format("A")
    name_list = [name.format(i) for i in "BCDE"]
    def __init__(self):
        pass
    
b=Stu_B()
print(b.name_list)

Stu_B this class cannot be created

error message: NameError: name" name" is not defined

in the Stu_A class, the other_name property is also formatted with the name attribute and works normally.

but in Stu_B, using a list generator to format the name attribute to create a list doesn"t work?

I hope a great god can give me an answer, thank you!

Mar.28,2021

For the correct explanation, please see from-a-list-comprehension-in-the-class-definition" rel=" nofollow noreferrer "> https://stackoverflow.com/que.

here.

this question involves two knowledge points:

    The scope of
  • Class Definition is very special and does not extend to other scopes within it (functions, deductions, subclass definitions)
  • in Python 3, in order to prevent variable pollution, deduction has its own scope

if you have to do this, it's not impossible to use lambda to create an immediate execution function:


python3:

[name.format(i) for i in 'BCDE']

is equivalent to:

list(name.format(i) for i in 'BCDE')

this is a function call. So if you want to reference the class attribute name as a function variable, you should go like this:

[.name.format(i) for i in 'BCDE']
Menu