2

I wonder if there is a way to get the class name automatically upon defining class attribute before initialization

class MyClass(object):
    attribute1 = 1
    attribute2 = 2 # This a simple example, MyClass has many other attributes
    print className # normally one would use self.__class__.__name__ but self or cls are not defined at the level

    def __init__(self):
        a = 1

Purpose

In the framework I am working in, attribute1 and attribute2 are object instances (you will say everything is object oriented in python :) ) I want to set the class name to those attributes prior to MyClass initialization. MyClass get initialized a lot of times and it has much more than 2 attributes which makes the operation very time consuming to do at every initialization

Cobry
  • 4,348
  • 8
  • 33
  • 49
  • Why would you need it prior to initialization? The class will not run until it is initialized so I don't really see the point. – asdf Sep 16 '14 at 17:13
  • You can use a metaclass -- But I'm not sure exactly how much that helps you since you haven't said _why_ you need the class name. Perhaps if you tell us what you're actually trying to accomplish here we can point you in a different direction. – mgilson Sep 16 '14 at 17:16
  • It's not clear what you are trying to do, but you should take a look at metaclasses :) – Wolph Sep 16 '14 at 17:16
  • In the framework I am working in, attribute1 and attribute2 are object instances (you will say everything is object oriented in python :) ) I want to set the class name to those attributes prior to MyClass initialization. MyClass get initialized a lot of times and it has much more than 2 attributes which makes the operation very time consuming to do at every initialization – Cobry Sep 16 '14 at 17:26
  • 1
    What does "set the class name to those attributes" mean? Do you mean pass the attributes to the `__init__` function? What *exactly* are you trying to do? – Daniel Roseman Sep 16 '14 at 17:29

1 Answers1

0

A metaclass can be used to set an attribute with the class name before the class initialises:

class MyClassMeta(type):
    def __init__(self, name, bases, attrs):
        super(MyClassMeta, self).__init__(name, bases, attrs)
        # Set class_name to the name of our class; in this case "MyClass"
        self.class_name = name

class MyClass(object):
    __metaclass__ = MyClassMeta

    def __init__(self):
        # Prints "MyClass"
        print(self.class_name)

See this answer for a detailed explanation of metaclasses.

Community
  • 1
  • 1
Sam Hooke
  • 21
  • 5