Python class inherits object

0 votes

Is there any reason for a class declaration to inherit from object?

I just found some code that does this and I can't find a good reason why.

class MyClass(object):
    # class code follows...
Aug 30, 2018 in Python by bug_seeker
• 15,510 points
804 views

1 answer to this question.

0 votes

Python 3.x:
class MyClass(object): = new-style class
class MyClass: = new-style class (implicitly inherits from object)

Python 2.x:
class MyClass(object): = new-style class
class MyClass: = OLD-STYLE CLASS

Explanation:

When defining base classes in Python 3.x, you’re allowed to drop the object from the definition. However, this can open the door for a seriously hard to track problem…

Python introduced new-style classes back in Python 2.2, and by now old-style classes are really quite old. Discussion of old-style classes is buried in the 2.x docs, and non-existent in the 3.x docs.

The problem is, the syntax for old-style classes in Python 2.x is the same as the alternative syntax for new-style classes in Python 3.x. Python 2.x is still very widely used (e.g. GAE, Web2Py), and any code (or coder) unwittingly bringing 3.x-style class definitions into 2.x code is going to end up with some seriously outdated base objects. And because old-style classes aren’t on anyone’s radar, they likely won’t know what hit them.

So just spell it out the long way and save some 2.x developer the tears.

answered Aug 30, 2018 by Priyaj
• 58,020 points

Related Questions In Python

0 votes
1 answer

Python class inherits an object

Python 3.x: class MyClass(object): = new-style class class MyClass: ...READ MORE

answered Apr 17, 2018 in Python by anonymous
1,880 views
0 votes
1 answer

Python: For loop to iterate class object

Refer to the below code: class Try: ...READ MORE

answered May 22, 2019 in Python by Raj
8,148 views
0 votes
1 answer
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
0 votes
1 answer

Convert string list of dict from csv into JSON object in python

You can use the ast module Ex: import ast s = """[{'10': ...READ MORE

answered Sep 12, 2018 in Python by Priyaj
• 58,020 points
2,557 views
0 votes
1 answer

Convert string list of dict from csv into JSON object in python

You can use the ast module Ex: import ast s = """[{'10': ...READ MORE

answered Sep 24, 2018 in Python by Priyaj
• 58,020 points
1,030 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP