gt6989b
gt6989b

Reputation: 4203

Using Python class name to define class variables

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

Upvotes: 1

Views: 75

Answers (2)

Chris
Chris

Reputation: 22953

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.

Upvotes: 6

llllllllll
llllllllll

Reputation: 16404

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)

Upvotes: 4

Related Questions