Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (object) do next to class name in python? [duplicate]

When you declare a class in python, I often see (object) written next to the class name.

class someClass(object):
    def __init__(self, some_variable):
        ...
    ...

Is this same as writing below?

class someClass: # didn't write (object) here.
    def __init__(self, some_variable):
        ...
    ...

I don't really see any difference in terms of how they function. Is it just a way to clarify that someClass is a subclass of object? and is it a good practice to explicitly write object when I make a class?

like image 722
chanpkr Avatar asked Oct 27 '13 03:10

chanpkr


People also ask

How do you duplicate a class object in Python?

Copy an Object in Python In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object.

What does the __ str __ do?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.

What is __ new __ in Python?

__new__ is static class method, while __init__ is instance method. __new__ has to create the instance first, so __init__ can initialize it. Note that __init__ takes self as parameter. Until you create instance there is no self . Now, I gather, that you're trying to implement singleton pattern in Python.

What is __ str __ called?

The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.


2 Answers

In Python 2, making someClass a subclass of object turns someClass into a "new-style class," whereas without (object) it's just a "classic class." See the docs or another question here for information on the differences between them; the short answer is that you should always use new-style classes for the benefits they bring.

In Python 3, all classes are "new-style," and writing (object) is redundant.

like image 178
jwodder Avatar answered Oct 26 '22 01:10

jwodder


In python 3.x, they are the same, when you declare:

class C:
    def __init__(self):
        ...

it inherits from object implicitly.

For more information visit this.

like image 36
Christian Tapia Avatar answered Oct 26 '22 02:10

Christian Tapia