How do I print class name in a method?

Question:

I made a method and called onto it with super() but I do not know how to write the name of the class in a print statement!

from abc import ABC, abstractmethod

class Clothing(ABC):
    @abstractmethod
    def desc(self):
        pass


class Shirt(Clothing):
    def desc(self):
        x = input('Enter a color: ')
        y = input('Enter the size: ')

        print(f"Your {self} is: {x}nAnd its size is: {y}")


class Jean(Shirt):
    def desc(self):
        super().desc()


# shirt = Shirt()
# shirt.desc()

jean = Jean()
jean.desc()

I tried printing self,
which, while it does kind of return the class name, it has this answer:

Your **<__main__.Jean object at 0x0000023E2C2D7D30>** is: red
And its size is: 32

Btw I started learning like a week ago so please do enlighten me

Asked By: Jecise

||

Answers:

instance.__class__.__name__

You need to access the __class__ attribute to get the class, then __name__ to get the class name.

class Foobar:
    ...

print(Foobar().__class__.__name__)
# Foobar

With your code, here is an example of usage:

class Jean(Shirt):
    def desc(self):
        super().desc()

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

jean = Jean()
print(jean.class_name())
# Jean
Answered By: Dorian Turba
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.