xyz
xyz

Reputation: 326

difference between different type of class naming

What is difference between both class naming conventions, both resulting in the same output?

class class_name:
    def func():
        print('1st class')


class class_name():
    def func():
        print('2nd class')

Upvotes: 1

Views: 80

Answers (2)

Felix
Felix

Reputation: 2668

The syntax with parenthesis defines an inheritance relationship. But to inherit no class is the same as using just the class.

Python DOC on class inheritance

Suppose you had a class called parent:

class parent:
    def f1(self):
        print("F1 in action!")

And you wanted to use things from parent in another class (usually a relationship like parent: generalisation, child: specialisation). You can derive from that class.

class child(parent):
    def f2(self):
        print("F2 in action!")

# Now use child.f2 OR child.f1!
c = child()
c.f1()
c.f2()

Upvotes: 3

Chen A.
Chen A.

Reputation: 11280

This is new class syntax vs old class syntax

From Python's wiki:

A "New Class" is the recommended way to create a class in modern Python.

A "Classic Class" or "old-style class" is a class as it existed in Python 2.1 and before. They have been retained for backwards compatibility. This page attempts to list the differences.

The syntax for the two types looks the same; "new-style", "old style", "classic", and variants are just descriptions that various people have used; Python hasn't yet settled on a specific official choice for the terminology.

The minor syntactic difference is that New Style Classes happen to inherit from object.

Regarding @Felix question, consider the following:

class A: pass
class B(): pass
class C(object): pass

print A.__mro__
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    A.__mro__
AttributeError: class A has no attribute '__mro__'

print B.__mro__
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    B.__mro__
AttributeError: class B has no attribute '__mro__'

print C.__mro__
(<class '__main__.C'>, <type 'object'>)

You explicity have to inhert from object; there is no default inheritance.

Upvotes: 1

Related Questions