Usage of 'object' in class creation


#1

What is the purpose of ‘object’ in putting it in brackets next to a class name.
E.g. -

class ClassName(object):
    def __init__(self):
         print("Hello")

#2

its the class of which ClassName inherits. All classes inherit from object, which is the base class (the way classes are implemented in python)


#4

Thanks :slightly_smiling_face:… but what would happen if I don’t write ‘object’ in it.


#5

With this header, ClassName inherits some attributes from the existing type, object

class ClassName(object):

Now let’s look at documentation for the built-in function, dir. As we can see, it can reveal attributes of a class.

Add this line at the end of your code, then execute the code …

print dir(ClassName)

You’ll see names of the attributes of the ClassName type. Run the code twice, once with object within the parentheses of the ClassName definition header, and once without object within those parentheses. You’ll see a difference in the output.

Although the attributes inherited from object might not be useful in the current Codecademy exercise, they may come in handy in other situations. You can Google the names of those attributes to get information about them, but within the context of the Learn Python track, their utility may seem a bit obscure.


#6

Thanks that info about ‘dir’ was useful :+1: But I’m getting the same attributes list even after removing ‘object’ from within the parenthesis. Please could you help me on this.:confused:


#7

Hmm, that’s puzzling. Here’s something similar that I ran in a Codecademy environment …

class A():
  pass

class B(object):
  pass

print "Attributes of A"
print dir(A)
print "Attributes of B"
print dir(B)

Output …

Attributes of A
['__doc__', '__module__']
Attributes of B
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

In the above, B has more attributes than A.

… not sure why it was different when you tried it with ClassName.

EDIT: Are you running your code on Codecademy, which uses Python 2.x, or in a Python 3.x environment outside of Codecademy? Some changes were made in Python 3.x.


#8

Ooh maybe that’s why… I’m running it on my Windows Terminal and in Python 3.6.3


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.