0

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)

Diego Aaron
  • 386
  • 1
  • 6
  • 19

2 Answers2

2

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?

zvone
  • 18,045
  • 3
  • 49
  • 77
1
  • 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.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271