TransWikia.com

difference in syntax of python class creation - class name_class: class name_class(): and class name_class(Object):

Stack Overflow Asked by Diego Aaron on February 11, 2021

I am learning OOP with Python and I consider that I have already understood the basics to understand how to create and instantiate a class but I have a question of syntax. Reviewing different examples to practice I have been able to see that a class can be created with slight differences but that I instantiate them in the same way (without problems).

# Form 1
class Dog:

    def __init__(self, name):
        self.name = name

    def ladrar(self):
        print("grrr", self.name, " - esta ladrando...")


# Form 2
class Cat():

    def __init__(self, name):
        self.name = name

    def mauyar(self):
        print("miau miau", self.name, " - esta mauyando...")


# Form 3
class Rat(object):

    def __init__(self, name):
        self.name = name

    def molestar(self):
        print("ggg ggg", self.name, " - esta molestando...")


# Creating objets
primerPerro = Dog("rufo")
primerPerro.ladrar()

primerGato = Cat("gaturra")
primerGato.mauyar()

primerraton = Rat("micky")
primerraton.molestar()


Check this documentation about classes in the Python files (LINK) and I can see that they use the first way to define the classes but I couldn’t find reference to the second and third way.

In which cases would the second and third form be used (they are correct forms)

2 Answers

This way, you define what classes your class inherits from:

class MyClass(SuperClass):

You can list multiple super classes, but even if you don't specify any, your class will always inherit from object, if you are in Python 3, so these are the same:

class MyClass(object):

class MyClass():

class MyClass:

However, in Python 2, classes did not inherit from object if you did not specify that, so there was a difference and most classes explicitly inherited from object.

See this for the explanation of what happens in Python 2: What is the difference between old style and new style classes in Python?

Answered by zvone on February 11, 2021

  • In Python 3-only code, you'd just use the first form (because the other forms are needlessly verbose and change nothing about the behavior on Python 3).

  • If you need to write code that still produces new-style classes when run on Python 2, you'd use the third form, and the other forms would produce old-style classes (which are generally inferior to new-style classes in the few cases where they differ). Given that Python 2 has reached end-of-life, I'd think twice before trying to write new code that supports it.

  • The second form serves no purpose, and should be avoided as a case of unnecessary parentheses disease.

Answered by ShadowRanger on February 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP