Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to inherit object in my Python classes? [duplicate]

I have seen both examples whereby developers inherit object and some do not. Is there any difference between the two approaches?

# case 1

class NoObj:
    pass


# case 2

class Obj(object):
    pass
like image 393
InfoLearner Avatar asked Oct 28 '25 10:10

InfoLearner


2 Answers

This only matters if you are using Python 2, class Foo() will create an old-style class so I suggest you always use class Foo(object): to create a new-style class.

But if you are using Python 3, class Foo: is the same as class Foo(): and class Foo(object):, so you can use any of those because all of them will create a new-style class. I personally use the first one.

like image 182
Julio Suriano Avatar answered Oct 29 '25 23:10

Julio Suriano


I have same question some time ego and do some quick search to found out, that in Python 3 you don't need to inherit object class any more. This is the stuff called "new style classes", that type of classes always inherits to object: https://wiki.python.org/moin/NewClassVsClassicClass

like image 39
Andrej Zacharevicz Avatar answered Oct 30 '25 00:10

Andrej Zacharevicz