Difference between class classname: AND class classname (): AND class classnamename (object):

I study python and imagine myself OOP. However, I'm struggling to figure out how best to create classes and, in particular, what is the difference between the following class definitions and when I should use them each:

class my_class:
  content...

class my_class():
  content...

class my_class(object):
  content...

I read the very useful python online help, although I did not find a specific answer to this question. Therefore, any ideas or recommended links will be appreciated, thanks.

+4
source share
2 answers

Well, I can immediately say that there is nothing special about the second method:

class my_class():
  content...

. , Python , @chepner. , (, ) , () , .


, Python .

Python 2.x

:

class my_class:
  content...

Python 2.2 . Python :

() : x , x.__class__ x, type(x) <type 'instance'>. , , , , .

Python 2.2 , object :

class my_class(object):
  content...

, . , :

... . x - , type(x) x.__class__...

, . SO, .

Python 3.x

Python 3.x object , , .

, :

class my_class(object):
  content...

:

class my_class:
  content...

. , object, Python.

+5

Python 2.2 +:

A B , C :

class A:
    pass

class B():
    pass

class C(object):
    pass


>>> A.__dict__
{'__module__': '__main__', '__doc__': None}

>>> B.__dict__
{'__module__': '__main__', '__doc__': None}

>>> C.__dict__
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

. . Guido van Rossum , python .

:

http://python-history.blogspot.com/2010/06/new-style-classes.html

http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes

+1

Source: https://habr.com/ru/post/1533746/


All Articles