class naming; whats the difference? [duplicate] - python

Why does the following class declaration inherit from object?
class MyClass(object):
...

Is there any reason for a class declaration to inherit from object?
In Python 3, apart from compatibility between Python 2 and 3, no reason. In Python 2, many reasons.
Python 2.x story:
In Python 2.x (from 2.2 onwards) there's two styles of classes depending on the presence or absence of object as a base-class:
"classic" style classes: they don't have object as a base class:
>>> class ClassicSpam: # no base class
... pass
>>> ClassicSpam.__bases__
()
"new" style classes: they have, directly or indirectly (e.g inherit from a built-in type), object as a base class:
>>> class NewSpam(object): # directly inherit from object
... pass
>>> NewSpam.__bases__
(<type 'object'>,)
>>> class IntSpam(int): # indirectly inherit from object...
... pass
>>> IntSpam.__bases__
(<type 'int'>,)
>>> IntSpam.__bases__[0].__bases__ # ... because int inherits from object
(<type 'object'>,)
Without a doubt, when writing a class you'll always want to go for new-style classes. The perks of doing so are numerous, to list some of them:
Support for descriptors. Specifically, the following constructs are made possible with descriptors:
classmethod: A method that receives the class as an implicit argument instead of the instance.
staticmethod: A method that does not receive the implicit argument self as a first argument.
properties with property: Create functions for managing the getting, setting and deleting of an attribute.
__slots__: Saves memory consumptions of a class and also results in faster attribute access. Of course, it does impose limitations.
The __new__ static method: lets you customize how new class instances are created.
Method resolution order (MRO): in what order the base classes of a class will be searched when trying to resolve which method to call.
Related to MRO, super calls. Also see, super() considered super.
If you don't inherit from object, forget these. A more exhaustive description of the previous bullet points along with other perks of "new" style classes can be found here.
One of the downsides of new-style classes is that the class itself is more memory demanding. Unless you're creating many class objects, though, I doubt this would be an issue and it's a negative sinking in a sea of positives.
Python 3.x story:
In Python 3, things are simplified. Only new-style classes exist (referred to plainly as classes) so, the only difference in adding object is requiring you to type in 8 more characters. This:
class ClassicSpam:
pass
is completely equivalent (apart from their name :-) to this:
class NewSpam(object):
pass
and to this:
class Spam():
pass
All have object in their __bases__.
>>> [object in cls.__bases__ for cls in {Spam, NewSpam, ClassicSpam}]
[True, True, True]
So, what should you do?
In Python 2: always inherit from object explicitly. Get the perks.
In Python 3: inherit from object if you are writing code that tries to be Python agnostic, that is, it needs to work both in Python 2 and in Python 3. Otherwise don't, it really makes no difference since Python inserts it for you behind the scenes.

Python 3
class MyClass(object): = New-style class
class MyClass: = New-style class (implicitly inherits from object)
Python 2
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.

Yes, this is a 'new style' object. It was a feature introduced in python2.2.
New style objects have a different object model to classic objects, and some things won't work properly with old style objects, for instance, super(), #property and descriptors. See this article for a good description of what a new style class is.
SO link for a description of the differences: What is the difference between old style and new style classes in Python?

History from Learn Python the Hard Way:
Python's original rendition of a class was broken in many serious
ways. By the time this fault was recognized it was already too late,
and they had to support it. In order to fix the problem, they needed
some "new class" style so that the "old classes" would keep working
but you can use the new more correct version.
They decided that they would use a word "object", lowercased, to be
the "class" that you inherit from to make a class. It is confusing,
but a class inherits from the class named "object" to make a class but
it's not an object really its a class, but don't forget to inherit
from object.
Also just to let you know what the difference between new-style classes and old-style classes is, it's that new-style classes always inherit from object class or from another class that inherited from object:
class NewStyle(object):
pass
Another example is:
class AnotherExampleOfNewStyle(NewStyle):
pass
While an old-style base class looks like this:
class OldStyle():
pass
And an old-style child class looks like this:
class OldStyleSubclass(OldStyle):
pass
You can see that an Old Style base class doesn't inherit from any other class, however, Old Style classes can, of course, inherit from one another. Inheriting from object guarantees that certain functionality is available in every Python class. New style classes were introduced in Python 2.2

Yes, it's historical. Without it, it creates an old-style class.
If you use type() on an old-style object, you just get "instance". On a new-style object you get its class.

The syntax of the class creation statement:
class <ClassName>(superclass):
#code follows
In the absence of any other superclasses that you specifically want to inherit from, the superclass should always be object, which is the root of all classes in Python.
object is technically the root of "new-style" classes in Python. But the new-style classes today are as good as being the only style of classes.
But, if you don't explicitly use the word object when creating classes, then as others mentioned, Python 3.x implicitly inherits from the object superclass. But I guess explicit is always better than implicit (hell)
Reference

Related

Object class and Type class in Python [duplicate]

I am learning about metaclass and I see that every class is a subclass of type class in python but sometimes I see people are using object class but object class is also a subclass of type class then what is the difference between them?
object is not a subclass of type: it is an instance of type.
object, the class, is the root of all class hierarchy in Python - however as everything in Python is an instance, it has to have a "class" that when properly instantiated with the proper parameters results in it.
As it is an obvious "chicken and egg" paradox, after all, the class type itself must inherit from object, that part of the class hierarchy is hand-wired in loop: it would be impossible to replicate the same relationships in pure Python code.
And finally: a class being an instance of a metaclass is not the same as inheriting, or being a subclass of that metaclass: inheritance hierarchy is one thing, the metaclass, which is used to construct each class itself, is another, ortogonal thing.
So, to recap: all classes in Python are themselves instances of a "metaclass" - and the default metaclass is type. All classes in Python also inherit from object - and that includes type. The class object itself must also be an instance of type, and that relationship is hardcoded in the Python runtime source-code (which is written in C in the case of cPython)

what is the difference between type class and object class in python

I am learning about metaclass and I see that every class is a subclass of type class in python but sometimes I see people are using object class but object class is also a subclass of type class then what is the difference between them?
object is not a subclass of type: it is an instance of type.
object, the class, is the root of all class hierarchy in Python - however as everything in Python is an instance, it has to have a "class" that when properly instantiated with the proper parameters results in it.
As it is an obvious "chicken and egg" paradox, after all, the class type itself must inherit from object, that part of the class hierarchy is hand-wired in loop: it would be impossible to replicate the same relationships in pure Python code.
And finally: a class being an instance of a metaclass is not the same as inheriting, or being a subclass of that metaclass: inheritance hierarchy is one thing, the metaclass, which is used to construct each class itself, is another, ortogonal thing.
So, to recap: all classes in Python are themselves instances of a "metaclass" - and the default metaclass is type. All classes in Python also inherit from object - and that includes type. The class object itself must also be an instance of type, and that relationship is hardcoded in the Python runtime source-code (which is written in C in the case of cPython)

Learn Python the Hard Way: exercise 40 - what is "object" and "self" in class definition?

Below is some code from Learn Python The Hard Way
Exercise 40: Modules, Classes, And Objects
I can't seem to figure out why is there a parameter for class MyStuff(object).
What's the reason to put object in the parentheses?
class MyStuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print "I AM CLASSY APPLES!"
I have looked through some of the articles here on StackOverflow but failed to understand what's new object and old class object.
Could someone please explain the meaning of object in the class definition?
What happens if I leave that the parentheses empty when I declare my class?
Also there is a (self) argument for the 2 functions in the code.
In the book it says "self" is an empty object python created while instantiating an object with class.
But why stating the argument before the actual use of it??
I have been learning programming for 2 weeks only so I apologize if the question is too superficial, thank you for your time~
As per your comment, I see you are using Python 2. In Python 2.2 they introduced "New-style" classes, but kept "Classic" classes for backwards-compatibility reasons. In Python 3.0 or newer, classic classes are gone - every class is a new-style class (regardless of syntax).
For python 2.2-2.7, syntactically a new-style class is declared by subclassing from object explicitly (unless it has a different parent class):
class MyStuffNew(object):
a=1
while omitting the object reference creates a classic class:
class MyStuffClassic():
a=1
Functionally, they work almost the same, but there are a few differences between them in the builtin language definitions. For example, New-style classes introduced a builtin class method __mro()__ (method resolution order) which is used by the interpreter to work out which method (in the class inheritance heirarchy) you meant to call. This inbuilt method is missing in old-style classes (and the method resolution order is different, which can lead to some unexpected behaviour). For more information about New-style vs Classic classes, please read this Python Wiki page.
As mentioned above, in Python3 or above, the syntax used doesn't matter; all classes are new-style. However, many coders will use the class MyClass(object): syntax to maintain code compatibility with Python2.7. - Please see this answer.
In any version of the Python language, class MyChildClass(ParentClass): defines an inheritance relationship - MyChildClass is a child of ParentClass and will inherit all of its methods and fields.
The self is the way Python knows this is a member method and not a static function of your class. You can only access member fields and methods from within your class by using self.field and self.myMethod(var1,var2), etc.
When you actually call these functions from other places in your code, you don't pass a value to self - it is the variable that you are using. For example:
stuff = MyStuff()
stuff.apple()
# outputs "I AM CLASSY APPLES!"
print stuff.tangerine
# outputs "And now a thousand years between"
stuff.tangerine = "Something else."
print stuff.tangerine
# outputs "Something else."
stuff2 = MyStuff()
print stuff2.tangerine
# outputs "And now a thousand years between"
If you don't include self in the method definition, calling mystuff.apple() will result in a runtime error because implicitly it's the same thing as calling MyStuff.apple(mystuff) - passing the instance of your MyStuff class into the apple function.

Difference between class declarations

I see some similar questions about this topic, but i wish to be sure, so i am asking...
What is the difference between:
class MyClass:
pass
and
class MyClass():
pass
Also, is there a difference between these two:
class MyClass():
pass
class MyClass(object):
pass
There is no difference between class MyClass and class MyClass(). The second question is dependent on your python version. On python3.x, there is no difference -- On python2.x, the latter (where you inherit from object) creates a new-style class rather than an old-style class. In python3.x, ALL classes are new-style. New style classes are preferred these days -- As such, I always make sure that my classes inherit from object.
There is no difference between the first two spellings.
In python 2.7, there is a huge difference between the latter two. Inheriting from object makes it a new-style class, changing the inheritance semantics and adding support for descriptors (#property, #classmethod, etc.). It's the default in Python 3.
New-style classes were introduced in Python 2.2 to unify types (such as int and list), and classes, and because several things change in backwards-incompatible ways, you need to 'opt in', explicitly inherit from object to enable the changes.
In Python 3, inheriting from object is no longer needed, classes are new-style, always.
Class declarations of the type class MyClass(object) are New Style classes on Python 2.x
Guido writes about some of the thinking that brought about the new classes in the History of Python

In Python, what is the difference between "class name(object):" and "class name():"

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
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.
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:
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.
In this case, none, because the first explicitly inherits from object as a base class, while the second inherits from object implicitly.

Categories

Resources