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
Related
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
I have read answers for this question: What are metaclasses in Python? and this question: In Python, when should I use a meta class? and skimmed through documentation: Data model.
It is very possible I missed something, and I would like to clarify: is there anything that metaclasses can do that cannot be properly or improperly (unpythonic, etc) done with the help of other tools (decorators, inheritance, etc)?
That is a bit tricky to answer -
However, it is a very nice question to ask at this point, and there are certainly a few things that are easier to do with metaclasses.
So, first, I think it is important to note the things for which one used to need a metaclass in the past, and no longer needs to: I'd say that with the release of Python 3.6 and the inclusion of __init_subclass__ and __set_name__ dunder methods, a lot, maybe the majority of the cases I had always written a metaclass for (most of them for answering questions or in toy code - no one creates that many production-code metaclasses even in a lifetime as a programmer) became outdated.
Specially __init_subclass__ adds the convenience of being able to transform any attribute or method like class-decorators, but is automatically applied on inheritance, which does not happen with decorators.
I guess reading about it was a fator motivating your question - since most metaclasses found out in the wild deal with transforming these attributes in __new__ and __init__ metaclass methods.
However, note that if one needs to transform any attribute prior to having it included in the class, the metaclass __new__ method is the only place it can be done. In most cases, however, one can simply transform it in the final new class namespace.
Then, one version forward, in 3.7, we had __class_getitem__ implemented - since using the [ ] (__getitem__) operator directly on classes became popular due to typing annotations. Before that, one would have to create a metaclass with a __getitem__ method for the sole purpose of being able to indicate to the type-checker toolchain some extra information like generic variables.
One interesting possibility that did not exist in Python 2, was introduced in Python 3, then outdated, and now can only serve very specific cases is the use of the __prepare__ method on the metaclass:
I don't know if this is written in any official docs, but the obvious primary motivation for metaclass __prepare__ which allows one custom namespace for the class body, was to return an ordered dict, so that one could have ordered attributes in classes that would work as data entities. It turns out that also, from Python 3.6 on, class body namespaces where always ordered (which later on Python 3.7 were formalized for all Python dictionaries). However, although not needed for returning an OrderedDict anymore, __prepare__ is still aunique thing in the language in which it allows a custom mapping class to be used as namespace in a piece of Python code (even if that is limited to class bodies). For example, one can trivialy create an "auto-enumeration" metaclass by returning a
class MD(dict):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.counter = 0
def __missing__(self, key):
counter = self[key] = self.counter
self.counter += 1
return counter
class MC(type):
#classmethod
def __prepare__(mcls, name, bases, **kwd):
return MD()
class Colors(metaclass=MC):
RED
GREEN
BLUE
(an example similar to this is included in Luciano Ramalho's 'Fluent Python' 2nd edition)
The __call__ method on the metaclass is also peculiar: it control the calls to __new__ and __init__ whenever an instance of the class is created. There are recipes around that use this to create a "singleton" - I find those terrible and overkill: if I need a singleton, I just create an instance of the singleton class at module level. However, overriding typing.__call__ offers a level of control on class instantiation that may be hard to achieve on the class __new__ and __init__ themselves. But this definitely can be done by correctly keeping the desired states in the class object itself.
__subclasscheck__ and __instancecheck__: these are metaclass only methods, and the only workaround would be to make a class decorator that would re-create a class object so that it would be a "real" subclass of the intended base class. (and that is not always possible).
"hidden" class attributes: now, this can be useful, and is less known, as it derives from the language behavior itself: any attribute or method besides the dunder methods included in a metaclass can be used from a class, but from instances of that class. An example for this is the .register method in classes using abc.ABCMeta. This contrasts with ordinary classmethods which can be used normally from an instance.
And finally, any behavior defined with the dunder methods for a Python object can be implemented to work on classes if they are defined in the metaclass. So if you have any use case for "add-able" classes, or want a special repr for your classes, just implement __add__ or __repr__ on the metaclass: this behavior obviously can't be obtained by other means.
I think I got all covered there.
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.
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.
In python, why is recommended to inherit any class we make from the class object , why not directly make it as the base class??
An important thing I noticed is that the declaration __slots__ does not work if I make my class as a base class (instead as a subclass of the class object).
What other advantages/disadvantages do I have by inheriting my class from the class object?
In Python2, you must inherit from object in order to create a "new-style" class. Things like descriptors, super and __slots__ do not work correctly with "old-style" classes, but old-style classes remained for backwards compatibility.
In Python3, all classes are new-style classes, so inheriting from object is no longer necessary.
when you inheriting from the object you create new style class, without it you have old style class see: http://www.python.org/doc/newstyle/ for more