What information does type() return for user defined classes?

Question

If the type() function is used on a user-defined class, what information is returned?

Answer

The type() function will return the namespace and class name for the object. The top-level code for a Python program has a namespace of __main__ (unless the code is part of a module). The following code example shows the information returned for a list, a dictionary, and a user-defined class.

class TestClass:
    def __init__(self):
        self.value = 0

    def getVal(self):
        return self.value

mylist = [1,2,3]
mydict = { "A": 1, "B": 2}
myobj = TestClass()

print(type(mylist))
# <class 'list'>
print(type(mydict))
# <class 'dict'>
print(type(myobj))
# <class '__main__.TestClass'>
9 Likes

No, it returns the class

3 Likes

6 posts were split to a new topic: DATA TYPES vs. DATA STRUCTURES

I dont understand what the top part has to do with the rest of the answer.
class TestClass:

def init(self):
self.value = 0

def getVal(self):
    return self.value

I get where the TestClass comes into play as you used that below to print what type it is, but where are we getting the list and dictionary from it?
Thanks.

Hi @cloud5565327245 ,

The lines that create the list ‘my_list’ and the dictionary ‘my_dict’ do not make use of the class ‘TestClass’.

mylist = [1,2,3]
mydict = { “A”: 1, “B”: 2}

Within the class, the init is used to initialize the object. So, when we create an object of type ‘TestClass’, using

myobj = TestClass()

we are creating the object that has one attribute called ‘value’. The attribute is zero when the object is created, and if we call the method getVal on myobj, we get zero ‘0’.
We can change the value, like so:

myobj.value = 2

if we call the method getVal on myobj after changing myobj’s ‘value’, we would get 2.

print(myobj.getVal())

Now that makes complete sense. Thank you so much!