Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python class definition [duplicate]

Tags:

python

some time i see some classes defined as subclass of object class, as

class my_class(object):
    pass

how is if different from the simple definition as

class my_class():
    pass
like image 630
Bunny Rabbit Avatar asked Mar 10 '11 14:03

Bunny Rabbit


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.

Can you copy an instance of a class in Python?

Yes, you can use copy. deepcopy . so just c2 = copy.

How do you duplicate something in Python?

Copying Arbitrary Python Objects Its copy. copy() and copy. deepcopy() functions can be used to duplicate any object.

How do you copy from one class to another in Python?

Creating a class that inherits from another class To create a class that inherits from another class, after the class name you'll put parentheses and then list any classes that your class inherits from. In a function definition, parentheses after the function name represent arguments that the function accepts.

What is self __ dict __ Python?

__dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects.


3 Answers

This syntax declares a new-style class.

like image 55
Björn Pollex Avatar answered Oct 23 '22 14:10

Björn Pollex


The first one is a new style class and the second is the old style class.

EDIT

In [1]: class A:
   ...:     pass
   ...: 

In [2]: class B(object):
   ...:     pass
   ...: 

In [3]: a = A()

In [4]: b = B()

In [5]: dir(a)
Out[5]: ['__doc__', '__module__']

In [6]: dir(b)
Out[6]: 
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']
like image 43
gruszczy Avatar answered Oct 23 '22 15:10

gruszczy


For Python 3.x, there is no difference. In Python 2.x, deriving from object makes a class new-style, while providing no base classes will give you an old-style class.

like image 3
Sven Marnach Avatar answered Oct 23 '22 13:10

Sven Marnach