Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deriving class from `object` in python

So I'm just learning python (I know plenty of other languages) and I'm confused about something. I think this is due to lack of documentation (at least that I could find). On a few websites, I've read that you should derive your classes from object:

  class Base(object):     pass  

But I don't see what that does or why or when you should do it. Is there official documentation on this that I've missed? Is this a 3.x feature?

like image 476
Falmarri Avatar asked Aug 02 '10 01:08

Falmarri


People also ask

Do all classes inherit from object in Python?

Each class in Python, by default, inherits from the object base class.

How do you derive a class from another class in Python?

Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.

What are derived classes in Python?

Classes that inherit from another are called derived classes, subclasses, or subtypes. Classes from which other classes are derived are called base classes or super classes. A derived class is said to derive, inherit, or extend a base class.


2 Answers

Mostly it isn't going to matter whether or not you inherit from object, but if you don't there are bugs waiting to catch you out when you've forgotten that you decided not to bother.

Some subtle things just won't work properly if you don't ultimately inherit from object:

  1. Using properties in classic classes only partly works: get works alright, but set does weird things.
  2. Multiple inheritance behaves differently in classic classes than in classes derived from object.
  3. Also multiple inheritance won't work if you try to mix classic classes with those that subclass object. Whatever you do you want to be consistent.

Some people are fine with continuing to use classic classes except when they need the new behaviour, others say to always use new style classes to avoid later shooting yourself in the foot. If you're working on a single person project do whatever is good for you; if its a shared project be consistent with the other developers.

like image 180
Duncan Avatar answered Oct 31 '22 19:10

Duncan


In Python 3, classes extend object implicitly, whether you say so yourself or not.

See here.

like image 34
stenci Avatar answered Oct 31 '22 19:10

stenci