7

What is the difference between the two classes below? Do you have some related information about this case? Thank you very much.

class test(object):
  def __init__(self, name):
     print name

class test():
  def __init__(self, name):
     print name
Kevin
  • 74,910
  • 12
  • 133
  • 166
xiaoke
  • 253
  • 1
  • 4
  • 9

3 Answers3

4

In python 2.x, the class that inherits from object will be a new-style class, while the other won't, while in python 3.x there'll be both new-style.

However, the differences between new and old are rather advanced, (for example, attribute search order) so a beginner shouldn't be too concerned about the incompatibilities.

See this answer for more information if you're interested, but it's rather a thing for library developers etc.

Community
  • 1
  • 1
unddoch
  • 5,790
  • 1
  • 24
  • 37
4

Mhmm ... this wiki-page explains the differences very illustratively: http://wiki.python.org/moin/NewClassVsClassicClass

And I saw some answeres with the information, that Old-(Classic)-Style and New-Style classes are the same in py3 -> that's not correct:

enter image description here Old-style classes are removed in Python 3, leaving only the semantics of new-style classes

Besides this, the New-Style classes are quite available since Python 2.2. Up to 2.1 we have had to use the Classic style -> see here

Short summary about the differences/infos could be:

  • New-Style classes are available since Python 2.2
  • New-Style classes can use descriptors - Old Style classes cannot
  • New Style classes can subclass most built-in types - Old Style classes cannot
  • New Style classes supports a new meta-model (which affects e.g. the behaviour of the type() built-in massively)
  • Old-Style classes will find an attribute on an instance before it looks in the hierarchy - New-Style classes will let the class definition win if it is a writeable descriptor
  • Old-Style classes has been removed in Python 3

But in most way the introduction of the New-style classes has been affected within the comming up of python's Descriptors --> read more here.

Colin O'Coal
  • 1,377
  • 10
  • 10
-3

In this case, none, because the first explicitly inherits from object as a base class, while the second inherits from object implicitly.

Bradley Swain
  • 804
  • 5
  • 12
  • There is a difference. Check `test.__mro__` for the first class. The second class throws an `AttributeError`. – Blender Sep 14 '12 at 15:32