Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Old-style and new-style classes in Python 2.7 [duplicate]

Possible Duplicate:
Old style and new style classes in Python

What is the current state of affairs with new-style and old-style classes in Python 2.7?

I don't work with Python often, but I vaguely remember the issue. The documentation doesn't seem to mention the issue at all: The Python Tutorial: Classes. Do I still need to worry about this? In general, should I declare my classes like the following?

class MyClass:     pass 

or?

class MyClass(object):     pass 
like image 880
User Avatar asked Dec 11 '12 09:12

User


People also ask

What is the difference between old style and new style classes in Python?

A new-style class is a user-defined type, and is very similar to built-in types. Old-style classes do not inherit from object . Old-style instances are always implemented with a built-in instance type. In Python 3, old-style classes were removed.

Does Python 2.7 support classes?

Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name.


2 Answers

Always subclass "object". Those are new style classes.

  • You are ready for Python 3 that way.

  • Things like .super() work properly that way, should you need them.

like image 146
Reinout van Rees Avatar answered Sep 20 '22 00:09

Reinout van Rees


You should always use new style classes. New-style classes are part of an effort to unify built-in types and user-defined classes in the Python programming language.

New style classes have several things to offer such as:

  • Properties: Attributes that are defined by get/set methods
  • Static methods and class methods
  • The new getattribute hook, which, unlike getattr, is called for every attribute access, not just when the attribute can’t be found in the instance
  • Descriptors: A protocol to define the behavior of attribute access through objects
  • Overriding the constructor new
  • Metaclasses

Source.

like image 27
NlightNFotis Avatar answered Sep 18 '22 00:09

NlightNFotis