How to return the name of a class to be used as an argument

319 views Asked by At

I'm a bit new to programming and didn't really know how to search for the answer to this particular problem so I thought I'd share an example to get my point across. I'm currently writing a script that will add an instance of my class (named applicant) to a mongo database elsewhere. My problem is that in many of my methods, I need to return the name of a class from a function such that the returned value can be used as a parameter in another call. Here's an example

modelName = get_class().getModelName()

In the above code, I am trying to retrieve the name of a particular data-model in question. My idea for this was to write two methods, one for returning the name of the class where the model name can be found, and another for returning the actual model name. This is done in an abstract class so that the functionality of my subclasses can be generalized (otherwise I would just put the model name and class name directly). What I'm unsure about is how to write a method that will return the name of the class in a format that is compatible with the above use. So for example, if I write the method in a class called Rushee, then it should be able to return a 'rushee' in a way where rushee.getModelName() will work.

Any ideas would be incredibly helpful. Thank you!

5

There are 5 answers

0
sudo On

To get the name of the class you can use this code

class SomeClass():
    def getName(self):
        return self.__class__.__name__
0
this be Shiva On

IIUC, you can use the __class__ attribute of an object to get the name of the class that it is an instance of.

In [60]: class Foo():
    ...:     pass
    ...:     
    ...:     

In [61]: x.__class__
Out[61]: __main__.Foo

This returns the fully qualified name (including the namespace the object belongs to), so to get only the last part, you'd do x.__class__.__name__.

0
Reblochon Masque On

Here is one method

class Grid:
    pass

g = Grid()
type(g).__name__

This is similar to what COLDSPEED posted earlier:

g.__class__.__name__
0
AudioBubble On

In an class hierarchy:

class A():
    def get_class_name(self):
        return self.__class__.__name__

class B(A):
    pass

b = B()

print(b.get_class_name())

OUTPUT:

B
0
user4390931 On
class Rushee:
    def get_model_name(self):
        return "return something"


class Other:
    def __init__(self):
        self.rushee = Rushee()

    def class_name(self):
        return self.rushee.__class__.__name__


if __name__ == "__main__":
    other = Other()
    other.class_name()