1

I have a class

class MyClass(object):
    ClassTag = '!' + 'MyClass'

Instead of explicitly assigning 'MyClass' I would like to use some construct to get the class name. If I were inside a class function, I would do something like

@classfunction
def Foo(cls):
    tag = '!' + cls.__class__.__name__

but here I am in class scope but not inside any function scope. What would be the correct way to address this?

Thank you very much

2
  • 2
    Fix your typo of class definition first... Commented Mar 21, 2018 at 21:21
  • Thank you, was typing from head on auto-think :) not from code -- put in def instead of class -- now fixed. Commented Mar 22, 2018 at 3:22

2 Answers 2

6

Instead of explicitly assigning 'MyClass' I would like to use some construct to get the class name.

You can use a class decorator combined with the __name__ attribute of class objects to accomplish this:

def add_tag(cls):
    cls.ClassTag = cls.__name__
    return cls

@add_tag
class Foo(object):
    pass

print(Foo.ClassTag) # Foo

In addition to the above, here are some side notes:

  • As can be seen from the above example, classes are defined using the class keyword, not the def keyword. The def keyword is for defining functions. I recommend walking through the tutorial provided by Python, to get a grasp of Python basics.

  • If you're not working on legacy code, or code that requires a Python 2 library, I highly recommend upgrading to Python 3. Along with the fact that the Python Foundation will stop supporting Python in 2020, Python 3 also fixes many quirks that Python 2 had, as well as provides new, useful features. If you're looking for more info on how to transition from Python 2 to 3, a good place to start would be here.

Sign up to request clarification or add additional context in comments.

3 Comments

@liliscent beautiful post at the same time with the exact same named content haha. :p
Thank you, was typing from head on auto-think :) not from code -- put in def instead of class -- now fixed. Very clever, thanks
Glad I could help @gt6989b!
4

A simple way is to write a decorator:

def add_tag(cls):
    cls.ClassTag = cls.__name__
    return cls

# test

@add_tag
class MyClass(object):
    pass

print(MyClass.ClassTag)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.