Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get aliased name of an imported class

Tags:

python

alias

I have a module named 'mymod' which defines a class named MyClass.

class MyClass:
    def __init__ (self):
        pass

From the main module, this class is imported as Imp_MyClass, and an object is created.

from mymod import MyClass as Imp_MyClass
o = Imp_MyClass()

To print the name of the class from this object, we use

print o.__class__.__name__

which prints 'MyClass'. What should I do to print its aliased name, viz. 'Imp_MyClass'?

like image 856
Krishnendu Avatar asked Dec 20 '14 11:12

Krishnendu


Video Answer


1 Answers

There is no way to print its aliased name. Many names can refer to the same class. Classes in Python are just values like any other, and they can be assigned to names arbitrarily. Your import statment is just an assignment.

It's like asking, how can I find the name of the object in this scenario:

a = b = c = MyClass()
d = a

Which name is "the real" name? All of a, b, c, and d refer to the object, no name is more right than any other.

In your code you can do:

from mymod import MyClass as Imp_MyClass
AlsoMyClass = Imp_MyClass
AnotherOne = AlsoMyClass
o = AlsoMyClass()
o2 = AnotherOne()

Which class name is "right"?

like image 131
Ned Batchelder Avatar answered Oct 07 '22 07:10

Ned Batchelder