14
class SomeClass:
    SOME_CONST = "hello"
    SOME_OTHER_CONST = SomeClass.SOME_CONST + " world"

This doesn't work.

NameError: name 'SomeClass' is not defined

Is there any way to refer to the class within the class?

Aram Kocharyan
  • 20,165
  • 11
  • 81
  • 96
  • 1
    Is there any particular reason you need the class name, or do you just need access to the other class attributes? You treat it as just another variable in the same scope, e.g. `SOME_OTHER_CONST = SOME_CONST` – Casey Kuball Apr 06 '12 at 05:22
  • This question was asked a few days ago. The short answer is no. The long answer is sometimes using a metaclass or something. See [here](http://stackoverflow.com/questions/9987018/why-does-self-outside-a-functions-parameters-give-a-not-defined-error/9987102#9987102) for an explanation of why. – aaronasterling Apr 06 '12 at 05:22

1 Answers1

24

You don't need the class name

class SomeClass:
   SOME_CONST = "hello"
   SOME_OTHER_CONST = SOME_CONST + " world"
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
  • @AramKocharyan PHP needs to reference the class to access a class variable because it has a more standard notion of class. In python, the VM enters a local scope and executes all code under the `class` statement as if it were a function. It then turns the resulting name space into the class. So you can do this in Python because it's already in the same name space. – aaronasterling Apr 06 '12 at 05:34
  • 1
    worth mentioning that order matters here, i.e. `SOME_CONST` cannot be defined after it's dereferenced – ijoseph Sep 29 '22 at 22:49