Python inheritance: when and why __init__

2024/9/8 8:32:23

I'm a Python newbie, trying to understand the philosophy/logic behind the inheritance methods. Questions ultimately regards why and when one has to use the __init__ method in a subclass. Example:

It seems a subclass inheriting from a superclass need not have its own constructor (__init__) method. Below, a dog inherits the attributes (name, age) and methods (makenoise) of a mammal. You can even add a method (do_a_trick) Everything works as it ``should", it seems.

However, if I wanted to add a new attribute in the subclass as I attempt to do in the Cats class, I get an error saying "self" is not defined. Yet I used "self" in the definition of the dog class. What's the nature of the difference? It seems to define Cats as I wish I need to use __init__(self,name) and super()__init__(name). Why the difference?

class Mammals(object):def __init__(self,name):self.name = nameprint("I am a new-born "+ self.name)  self.age = 0def makenoise(self):print(self.name + " says Hello")class Dogs(Mammals):def do_a_trick(self):print(self.name + " can roll over")class Cats(Mammals):self.furry = "True"  #results in error `self' is not definedmymammal = Mammals("zebra") #output "I am a new-born zebra"
mymammal.makenoise()  #output "zebra says hello"
print(mymmmal.age)    #output 0mydog = Dogs("family pet") #output "I am a new-born family pet"
mydog.makenoise()  #output "family pet says hello"
print(mydog.age)  # output 0
mydog.do_a_trick() #output "family pet can roll over"
Answer

Explicit is better than implicit.

However, you can do below:

class Dogs(Mammals):def __init__(self):#add new attributeself.someattribute = 'value'Mammals.__init__(self)

or

class Dogs(Mammals):def __init__(self):#add new attributeself.someattribute = 'value'super(Mammals, self).__init__()
https://en.xdnf.cn/q/72914.html

Related Q&A

TypeError: A Future or coroutine is required

I try make auto-reconnecting ssh client on asyncssh. (SshConnectManager must stay in background and make ssh sessions when need)class SshConnectManager(object): def __init__(self, host, username, passw…

Python socket closed before all data have been consumed by remote

I am writing a Python module which is communicating with a go program through unix sockets. The client (the python module) write data to the socket and the server consume them.# Simplified version of t…

Python child process silently crashes when issuing an HTTP request

Im running into an issue when combining multiprocessing, requests (or urllib2) and nltk. Here is a very simple code:>>> from multiprocessing import Process >>> import requests >>…

Shared variable in concurrent.futures.ProcessPoolExecutor() python

I want to use parallel to update global variable using module concurrent.futures in pythonIt turned out that using ThreadPoolExecutor can update my global variable but the CPU did not use all their pot…

MongoEngine - Another user is already authenticated to this database. You must logout first

Can anyone please explain why I am getting error Another user is already authenticated to this database. You must logout first when connecting to MongoDB using Flask MongoEngine?from mongoengine.conne…

How to bucketize a group of columns in pyspark?

I am trying to bucketize columns that contain the word "road" in a 5k dataset. And create a new dataframe. I am not sure how to do that, here is what I have tried far : from pyspark.ml.featur…

Dictionary of tags in declarative SQLAlchemy?

I am working on a quite large code base that has been implemented using sqlalchemy.ext.declarative, and I need to add a dict-like property to one of the classes. What I need is the same as in this ques…

How to connect to a GObject signal in python, without it keeping a reference to the connecter?

The problem is basically this, in pythons gobject and gtk bindings. Assume we have a class that binds to a signal when constructed:class ClipboardMonitor (object):def __init__(self):clip = gtk.clipboar…

openpyxl please do not assume text as a number when importing

There are numerous questions about how to stop Excel from interpreting text as a number, or how to output number formats with openpyxl, but I havent seen any solutions to this problem:I have an Excel s…

NLTK CoreNLPDependencyParser: Failed to establish connection

Im trying to use the Stanford Parser through NLTK, following the example here.I follow the first two lines of the example (with the necessary import)from nltk.parse.corenlp import CoreNLPDependencyPars…