1

I'm unclear on the namespace of the class name inside the class.

Here is an example:

class SomeClass():
    some_class_attribute = SomeClass.create_attribute()
    @classmethod 
    def create_attribute(cls, int): 
        return str(int) 

Is there any problem with the line some_class_attribute = SomeClass.create_attribute()?

When I'm writing a class in Spyder IDE, the class works, but Spyder displays a warning "Undefined name SomeClass".

user3731622
  • 4,844
  • 8
  • 45
  • 84
  • 1
    Have a look at [How can I access a classmethod from inside a class in Python](https://stackoverflow.com/questions/13900515/how-can-i-access-a-classmethod-from-inside-a-class-in-python) – bastelflp Nov 15 '17 at 21:48
  • 2
    The *class doesn't exist until after the class body is finished executing*. Therefore, you cannot use the class inside the class body (unless in a method). – juanpa.arrivillaga Nov 15 '17 at 21:52
  • @juanpa.arrivillaga What you said is what I was thinking. However, if I can't use the class inside the class body, why does it work? – user3731622 Nov 15 '17 at 23:19
  • 1
    @user3731622 this *does not work*, it raises a `NameError`, just as the IDE warns you it will. I suspect you have left-over variables in your interactive interpreter session (e.g., previous runs). – juanpa.arrivillaga Nov 15 '17 at 23:25
  • @juanpa.arrivillaga I was just checking that. What happened was, in Spyder I ran the script containing the class def without the attribute. Then I added the class atrribute which used the class name and ran the script again. Now I could access `SomeClass.some_class_attribute`. Seems like the interpreter got a little fooled and used the previously defined `SomeClass` name when it encountered the line `some_class_attribute = SomeClass.create_attribute()`. – user3731622 Nov 15 '17 at 23:30

0 Answers0