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.
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.
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.