Pavel Antspovich
Pavel Antspovich

Reputation: 1221

How to set `__class__.__name__` as class attribute?

I need to get class name from class:

class Cls:
    notation = None

    def __init__(self):
        notation = self.__class__.__name__

print(Cls.notation) prints None but I need 'Cls'

How to fix it or how to define class attribute which returns a name of class?

Upvotes: 1

Views: 774

Answers (1)

chepner
chepner

Reputation: 531075

You are assigning to a local variable, not the class attribute:

def __init__(self):
    Cls.notation = self.__class__.__name__

Note that self.__class__ isn't necessarily Cls, if there is a subclass of Cls involved. You might want to use

def __init__(self):
    type(self).notation = self.__class__.__name__

depending on your use case.

Assigning to self.notation won't work, because that creates an instance attribute that shadows the class attribute.

If you want Cls.notation == "Cls" immediately after the class is defined, you may as well just hard-code it:

class Cls:
    notation = "Cls"

or

class Cls:
    pass

Cls.notation = Cls.__name__

though you can also write

class Cls:
    notation = __qualname__

to set its value based on the name used in the first line of the statement, though __qualname__ takes into account nesting as well:

class Cls1:
    class Cls2:
        notation = __qualname__  # "Cls1.Cls2", not "Cls2"

Upvotes: 3

Related Questions