Get the alias of the name of the imported class

I have a module called 'mymod' that defines a class called 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 class name from this object, we use

 print o.__class__.__name__ 

which prints "MyClass". What should I do to print his aliases, namely. 'Imp_MyClass'?

+5
source share
2 answers

Cannot print aliases. Many names can belong to the same class. Classes in Python are just values, just like any other, and they can be assigned to names arbitrarily. Import status is just an assignment.

I like to ask how I can find the name of an object in this scenario:

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

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

In the code you can:

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

Which class name is "correct"?

+5
source

I agree with @ned's comments, but for your purpose you can easily create a new class by subclassing Imp_MyClass , which would be (almost) identical to the original class for almost all purposes:

 from mymod import MyClass class Imp_MyClass(MyClass): pass o = Imp_MyClass() 
0
source

Source: https://habr.com/ru/post/1209603/


All Articles