As part of this session, we will learn the following:
Example of Mulitple Inheritance
class Vehicle:
#dunder
def __init__(self, color, make, model="Good"):
self.color = color
self.make = make
self.model = model
self.speed = 0
#self.drag = 0
def __repr__(self):
return "My vehicle is:" + self.color + ":" + self.make + ":" + str(self.speed)
def run(self, speed):
self.speed = speed
veh1 = Vehicle("Red", "Toyota", "Corrola")
print(veh1)
print(veh1.color)
print(veh1.make)
print(veh1.model)
veh1.run(100)
print(veh1)
myvehs = [
Vehicle("Red", "Toyota1", "Corrola1"),
Vehicle("Reds", "Toyota2", "Corrola2"),
Vehicle("Redd", "Toyota3", "Corrola3"),
Vehicle("Redd", "Toyota4", "Corrola4")
]
for veh in myvehs:
print(veh)
class Car(Vehicle):
drag = 0
def do_drag(self, drag):
self.drag = drag
def __repr__(self):
return "My car is:" + self.color + ":" + self.make + ":" + " Drag: " + str(self.drag)
car = Car("Red", "Toyota", "Corrola")
print(car)
car.do_drag(90)
print(car)
class CarSports(Car, Vehicle):
fly = 0
def do_fly(self, fly):
self.fly = fly
def __repr__(self):
return "My car is:" + self.color + ":" + self.make + ":" + " Drag: " + str(self.drag) \
+ " Fly: " + str(self.fly)
carsports1 = CarSports("Red", "Toyota", "Corrola")
print(carsports1)
carsports1.do_fly(90)
print(carsports1)
Taking you to the next exercise in seconds...
Want to create exercises like this yourself? Click here.
No hints are availble for this assesment
Answer is not availble for this assesment
Please login to comment
95 Comments
class CalculationE:
x=0
y=10
Below is my code:
def __init__(self,a,b):
print('I am constructor')
self.x=a
self.y=b
def __del__(self):
print('I am destructor')
def sum_fun(self,a,b):
print(a+b)
def devide_fun(self,a,b):
print(a/b)
def multy_fun(self,a,b):
print(a*b)
def fun(self):
self.x=self.x+1
self.y=self.y-1
print(self.x,self.y)
class inher_Ex(CalculationE):
def __init__(self):
print('I am constructor of class 2')
def fun2(self):
print('I am insidefunction of class2')
obj1=CalculationE(6,7)
obj2=inher_Ex()
obj2.multy_fun(6,6)
obj2.fun2()
obj1.multy_fun(4,4)
Please help in my queries for each output
output:
Upvote ShareLet’s walk through the code execution step-by-step to understand the output and address your queries:
1. Object Creation and Constructor Call:
When you create
obj1 = CalculationE(6,7)
, the__init__
constructor ofCalculationE
is called, printing: 'I am constructor'.
2.
Destructor Call (__del__
):After the constructor runs, Python's garbage collector may call the destructor
__del__
forobj1
, even ifobj1
is still accessible. The destructor prints: 'I am destructor'.
This happens because Python tries to clean up objects when their reference count drops to zero or when the program has no use for them. However, this behavior can vary based on memory management, especially in an interactive environment like a REPL or IDE.3. Creating
obj2
:When you create
obj2 = inher_Ex()
, the__init__
constructor ofinher_Ex
is called, printing: 'I am constructor of class 2'.4. Destructor Call for
obj2
:Similarly, after
obj2
is created, Python may call the destructor__del__
forobj2
, printing: 'I am destructor'.
This is likely happening due to the garbage collection mechanism automatically cleaning up objects when they go out of scope or are no longer referenced.5. Multiplication Operation:
When
Upvote Shareobj2.multy_fun(6,6)
is called, it uses the method from the parent classCalculationE
, which multiplies the two numbers and prints '36'.Q: Why is the Destructor Called?
Garbage Collection in Python:
In Python, destructors (
__del__
) are called automatically by the garbage collector when an object is no longer needed. This might happen unexpectedly in your case due to how the garbage collector works in your environment (like an IDE or REPL). The garbage collector might think the object is out of scope or unused, even though it’s still referenced.Why Can You Still Use
obj1
After the Destructor is Called?The call to
__del__
does not immediately delete the object from memory; it just signals that the object is ready for cleanup. After__del__
is called, the object can still be accessible until it is actually removed from memory by the garbage collector. That’s whyobj1.multy_fun(4,4)
still works, even after the destructor is printed.Key Points:
Destructors are called automatically when Python thinks the object is no longer needed.
Garbage collection is unpredictable and may trigger at unexpected times, especially in interactive environments.
You can still use an object after
__del__
is called, depending on whether it’s actually deleted from memory.To better control when objects are cleaned up, avoid relying on destructors and use explicit object management techniques if needed.
Upvote ShareThen what is the use of destructor? If I am not creatining destructor then garbage collector will automatically clean the memory.
Upvote ShareYou're correct that in Python, the garbage collector automatically manages memory, and it will clean up objects when they are no longer in use, even if you don't define a destructor (
__del__
). So, why have a destructor at all? Let's break down the use cases for destructors:1. Resource Management (External Resources):
Destructors are useful when you're dealing with external resources like: File handles, Network connections, Database connections, External devices, Memory-mapped files. In these cases, you may want to ensure that resources are explicitly released when an object is destroyed. For example:
In this example, the destructor ensures that the file is properly closed when the object is destroyed. If you rely solely on the garbage collector, it may not close the file until much later, potentially causing resource leaks.
2. Custom Cleanup Logic:
Sometimes you might want to perform custom cleanup actions when an object is no longer needed. This can be more than just freeing memory—it might involve logging, resetting states, or releasing locks.
For example:
Here, the destructor allows you to perform some custom actions when the object is destroyed.
3. More Control Over Object Lifecycle:
While the garbage collector handles memory, there are situations where you want finer control over the lifecycle of an object. The destructor allows you to be explicit about what happens when an object is destroyed, and when combined with context managers (
with
statement), it gives you clear control over resource management.For example, combining destructors with context managers:
The
Upvote Share__exit__
method (similar to a destructor in this context) ensures that resources are properly released when the block finishes, even if an exception occurs.4. Garbage Collection Timing Is Uncertain:
The Python garbage collector's timing can vary depending on the environment (like different Python interpreters or systems), so you can't always predict when the object will be destroyed. If your object holds critical resources, relying solely on garbage collection may delay resource cleanup longer than desired. A destructor guarantees that cleanup happens as soon as the object is destroyed.
5. Handling Circular References:
In cases where you have circular references between objects, the garbage collector may have trouble collecting them. The destructor allows you to manually break such circular dependencies by explicitly releasing references.
Conclusion:
If you're only dealing with in-memory data (like variables, lists, dictionaries), you might not need to define a destructor. However, destructors are extremely useful when dealing with external resources or when you need to ensure specific cleanup tasks are performed at the time an object is destroyed. Without a destructor, the garbage collector will still free memory, but it won’t handle these other custom cleanup tasks for you.
1 Upvote ShareThe constructor is not automatically called while creating the object. If I put arguements while creating the object, it shows error. If I call the constructor separately with the arguements, it works
Can you please explain why is this happening?
Upvote ShareCan you share the code snippets of both the ways along with the error?
Upvote ShareLet's address the problems in your code.
Constructor Definition: In Python, the constructor method should be named
__init__
(with double underscores on each side). You've defined it as_init_
(single underscores), which is not recognized as the constructor method.Constructor Arguments: When you create an instance of a class in Python, the constructor (
1 Upvote Share__init__
method) is automatically called to initialize the object. If you define__init__
to accept certain arguments (likecolor
andsize
), you need to provide these arguments when creating an instance of the class.Thanks a lot for the clarifcation!
I am not able to import a module that is created locally.module name is my_lib.py which is created locally here.
from my_lib import interest, compoundinterest
from my_lib import *
Above statments are failing with below error.
Upvote Sharefile location:
Upvote ShareThis comment has been removed.
Please make sure there exists a function with the same name.
Upvote Shareis there any main method in python using class??
Upvote ShareHi,
Can you further ellaborate your question?
Upvote ShareAt 7:11
I do not underdstand.
self.x=self.x+1
what does . ,meamn??
can we use x=x+1 insted of self.x??
why self.x??
Upvote ShareHi,
It is the syntax of referring to a variable inside the class. If we don't use . , then a local or global variable x will be used. And to differentiate class variables, we use . sign with the variable.
Upvote ShareSir,
How can we call the destructor?
Is the position of the destructor within the class is of importance(like always mentioning in the end)?
Upvote ShareHi,
It can't be called manually but automatically. So when we destroy the object by 'del object', it gets called automatically.
The position of the destructor doesn't matter much. It's just a convention to mention them at last for code to be more clear so that in very large programs, we can check directly whether destructor is implemented or not by checking at the end, instead of searching in whole program.
Thanks
Upvote ShareIts giving me error while imprting from mylib.py
Upvote ShareHi,
Makesure there exists module named mylib, and that there is a function called compoundinterest inside that.
Thanks.
Upvote ShareSir,
How can we call the destructor?
Upvote ShareIs the position of the destructor within the class is of importance(like always mentioning in the end)?
Hi,
You can call the destructor explicitely by using the following command:
The desctructor is also called when an object goes out of reference or when the program ends.
Thanks.
Upvote ShareSir,
Upvote ShareThe initialisation of:
def __init__(self, nam): %it has two arguments
self.name = nam % initializing one variable with another.
I could not get the initialization part while we had two arguments. Sandeep Sir previously told that the ' . ' means the member of the current object but here in this initialization we are using one variable against another. Then how the object is getting defined when we call it with single argument 'Sally' ??
Hi,
Just as in the case of initializing with one variable, you can place multiple variables there to initialize with multiple variables. You can read more about them from the below link:
https://docs.python.org/3/tutorial/classes.html
Thanks.
1 Upvote ShareThank You for the reply, Sir. I will look into it.
Upvote ShareHi Team,
Have created a package and while calling the method getting this error:-
import Hardeep.Test
interest_rate(100,2,3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-13-730d93d3ff69> in <module> 1 import Hardeep.Test ----> 2 interest_rate(100,2,3) TypeError: 'module' object is not callable
Upvote ShareHi,
Please go through the below discussion for a probable explanation of the issue and a solution to the same:
https://stackoverflow.com/questions/18069716/why-am-i-getting-module-object-is-not-callable-in-python-3
Also, you can go through the below link to understand how to create Python packages:
https://packaging.python.org/tutorials/packaging-projects/
Thanks.
Upvote ShareHi Team,
I am not clear about packages, as i didn't find any practical in vedio, please assist.
Upvote ShareHi Team,
I have one doubt relared to constructor, As per the definiton the name of constructor should same as name of the class.but in vedio have seen a different way to create constructor for instance
In Python - def _init_(self ) :
In C# - Classname(){}
and Init itself a initialize method in C# but in Python as explained _init_(self) use to define constructor, can you please focus more on that.
Upvote ShareHi,
__init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor. The __init__ method can be called when an object is created from the class, and access is required to initialize the attributes of the class.
Thanks.
Upvote ShareI am getting this Error again and again after changing the text file name also. pls help me what is issue in this?
Hi,
This is because this library does not exist. To be able to import a library, that library needs to be present and installed. Try import numpy using the below command:
import numpy as np
Thanks.
Upvote Sharefile which we created in text format what we will do with that? that file i have saved with code and name of file is myglib, but in jupyter it is showing error .
Hi,
Could you please tell me which part of the video this is related to? You will find most of the codes from these lectures in our GitHub repository notebooks:
https://github.com/cloudxlab/ml/tree/master/python
Thanks.
Upvote ShareThis part is covered in modules at the end of video.
Upvote ShareHi, I am unable to see the content of module that was created using:
# To see a module
mylib.compoundinterest(100,5,2)
%cat mylib.py
************************************************************
Error Message:
*************************************************************************
Upvote ShareHi,
The file "mylib.py" should exist so that we could import it. So make sure it exists.
Thanks.
Upvote ShareHi,
The file exists as I had created it and stored it in the location '../ml/python'. Thus I was able to execute the previous code as :
**************************************************************
# So we use process as
import sys
sys.path.insert(1, '../ml/python')
import mylib
mylib.compoundinterest(100,5,2)
Output:
**********************************************************************
Hi,
Your present working directory is "/home/<username>/cloudxlab_jupyter_notebooks", whereas your file exists in different path. Hence the error. Hope this helps.
Thanks.
Upvote ShareHi,
I do understand that my module file is at different location than the cwd. So my question is:
1) Is there a way to specify the file from other path and still use %cat to see the module content? If yes, please let me know how to do it.
2) Do we have to change the cwd to the file path where the module file exists and then use % cat to view the module content?
Thanks for your help!
Upvote ShareHi,
Yes, you could still use "cat" to see the module content by using "! cat <filepath>". So here, it might be used as "!cat ../ml/python/mylib.py". Hope this helps.
Thanks.
Upvote ShareGreat.....Thanks !!!
Upvote ShareHi Bhaswati,
Can you please check the code again? if you're not able to find the error please post screenshot of full code.
Upvote ShareIn the method within the class definition:
x is a public variable and self refers to the object of the class.
Why self.x is used ? What does it actually mean? This syntax appears new to me.
Thanks.
Upvote ShareHi,
x is an attribute of the class. So, self.x means the attribute x of the class object.
Thanks.
Upvote SharePl help to fix this problem
Upvote ShareHi,
Could you please tell us what is the issue you are facing, also share a screenshot of the same if possible.
Thanks.
Upvote ShareThere are 4 questions:
Q- 1
@ 00:10:38 to 00:10:39
As Sandeep explained the value of ‘x’ is different for different objects because he has printed 2nd object ‘so’ only once, so the value automatically comes different. I understood what he is trying to say that value of ‘x’ is considered different as per the respective object when we call it, am it right?
Q- 2 (having screenshot)
What is the sequence of the program, how it is running, and giving the results, pls explain because I’m unable to get it?
Q- 3 (having screenshot)
@ 00:45:15 to 00:45:20
How to call if mylib file is in a different folder or somewhere else, what is the syntax how to write?
This means what is the code needs to write when we need to call the saved mylib file in some other folder means apart from root/tmp.
Q- 4
Most codes in the "Package" section were not running, showing some kinda error, pls check n explain why?
Hi,
1. That's correct! Value of 'x''here depends on the object.
2. When we create the object, the __init__ method is called. Next, the __del__ method is called. When we call the party method using the instance of the object created, the party method is executed.
3. Good question. Here is a link which would explain the concept in details:
https://realpython.com/absolute-vs-relative-python-imports/
4. Please be more elaborate on which codes you are referring to since this does not contain a 'package' section.
Thanks.
Upvote ShareThis comment has been removed.
2. okay , so here
3. Kewl , I'll check ...
4. i said most codes means pls check the video or notebook because I tried to run some and most were not working,,,, pls check video of package section and notebook,,,
Upvote ShareHi,
2. There name of the method is __del__ and not _del__.
4. Please let us know the codes you are facing challenge with by sharing a screenshot, along with a screenshot of the error and we would help you out with them.
Thanks.
1 Upvote ShareHow to import a module that exists in a location other than the current directory?
1 Upvote ShareHi,
Brilliant question!
Please go through the below link to find a detailed explanation:
https://stackoverflow.com/questions/4383571/importing-files-from-different-folder
Thanks.
Upvote ShareI observered, there is a concept of public, protected and private,
The public is a common variable without underscore (_) , can be accessable out side the class
The protected is also a common variable with single underscore(_) used for naming convention, but it should not restrict to access the variable outside the class.
The private is define the variable with double underscore(__) and we can not access that outside the class.
Ex:
class employee_private:
_age = 10 # Protected , but can be access out side, its naming conventation
__name = "" # protected attribute , can not acces
__salary = 0 # protected attribute , can not acces
def __init__(self, name, sal):
self.__name=name # protected attribute , can not acces
self.__salary=sal # protected attribute , can not acces
def getName(self):
return self.__name
emp_pro = employee_private('Madhu',3000)
-------------
Out[37]: emp_pro._age
-------------
emp_pro.__name
----------------
emp_pro.getName()
Out Put: 'Madhu'
Upvote ShareHi,
Are you facing any challenges?
Thanks.
Upvote ShareThis comment has been removed.
The destructor is showing its value as 2 in both the instances. How can i rectify this ?
Hi,
This is because you are calling it twice. Could you try the following:
Thanks.
Upvote Shareits showing the value of destructor as 1 now
Hi,
This is because that is the value of self.x while it is getting "destructed". If you are comparing this with the example given, there an.Party() was called 3 times, so the value of self.x was updated to 3.
Thanks.
Upvote ShareThis comment has been removed.
Hi,
Could you please tell me this is a part of which assessment?
Thanks.
Upvote ShareThis comment has been removed.
This comment has been removed.
Hi Team,
May i know reason for error and your class object were taking parameter, but not my below program
Hi,
First, you need to write __inti__ and not _init_. There are 2 underscores before and after init. Second, you need to check line 4, the variable name should be manager and not manger. Third, there are no dictionaries in your class, so line 5 and 6 would throw an error.
Thanks.
-- Rajtilak Bhattacharjee
Upvote ShareHi Sandeep/ Team,
I have defined a class with a constructor, a method and a destructor. I have then created an instance and called a method using the instance.Please find the screenshot.
Why is the destructor code getting executed immediately after the constructor code and not after the methods?
Hi,
Could you try creating one instance of the class and try again? It is working fine on my end.
Thanks.
-- Rajtilak Bhattacharjee
Upvote ShareHi Rajtilak, It does not seem to work. Even in the recording from Sandeep has the same issue.
Upvote ShareSir,
Upvote ShareCan the first argument be anything in place of self in the constructor function definition like other function definition in C language.
Hi,
self represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.
The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on.
self is parameter in function and user can use another parameter name in place of it.But it is advisable to use self because it increase the readability of code.
Thanks.
-- Rajtilak Bhattacharjee
Upvote ShareHi Sandeep/CloudX team,
I am unable to open any of the noetbook. I am constantly getting the error saying:
"An unknown error occurred while loading this notebook. This version can load notebook formats or earlier. See the server log for details."
Kindly help.
Thanks in Advance.
Upvote ShareHi,
Please let us know if you are still facing this issue.
Thanks.
-- Rajtilak Bhattacharjee
Upvote ShareSo, self here basically acts like the 'this' keyword of C++
Upvote Sharedoes,
self.attribute (in Python) equivalent to this->attribute (in C++)
?
Hi,
Yes, self is the equivalent of this of C++ in many respect.
Thanks.
-- Rajtilak Bhattacharjee
Upvote ShareHi Sandeep
i have created a file - mylib_interest.ipynb
in which I have defined functions:
def interest(p, r, t):
return (p*r*t)/100
def compoundinterest(p, r, t):
c = p;
for i in range(0, t):
c = c + c*r/100
return c - p
---------------------------------------------------------------------------
but when I am importing that module from different notebook its giving error:
import mylib_interest
-------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-13-39aa977a6e03> in <module>
----> 1 import mylib_interest.ipynb
ModuleNotFoundError: No module named 'mylib_interest'
Upvote ShareHi, Prashant.
You need to write the all your Python in the code in the notebook named "Python" which will be appearing on the right hand side.
Our compiler will be checking the path and variable from this notebook only.
So, creating another notebook will not be helpful for assessment purpose, for practising general things you can create another notebook.
All the best!
Upvote ShareHi Sandeep/CloudXlabs,
Upvote Shareif we don't define destructor in a class i.e __del__()
then, will the object will be deleted by itself or not by default?
how long it will reside in memory if we don't explicitly define destructor in a class?
Hi, Prashant.
In Python3, destructors are not needed as much needed in C++ because Python has a garbage collector that handles memory management automatically.
When a object functionality is finished
You can use
obj = Employee()
del obj --> When you want to delete all the references to the object.
All the best!
Upvote ShareWhat is the name of the book mentioned in this video when Sandeep was talking about the mathematics behind machine learning?
Upvote ShareProbably this one:
Upvote Sharehttps://www.amazon.com/Hand...
#sir am running this program
class partyAnimal:
x=0
def _init_(self):
print("I am constructed")
print("A party animal is born")
def party(self):
self.x=self.x+1
print("So far",self.x)
def _del_(self):
print("I am destructer",self.x)
an=partyAnimal()
an.party()
an.party()
an.party()
so=partyAnimal()
#output:-
So far 1
So far 2
So far 3
please tell me where, i am doing mistake.
Upvote SharePlease do indentation in below code:
class partyAnimal:
x=0
def _init_(self):
print("I am constructed")
print("A party animal is born")
def party(self):
self.x=self.x+1
print("So far",self.x)
def _del_(self):
print("I am destructer",self.x)
an=partyAnimal()
Upvote Sharean.party()
an.party()
an.party()
so=partyAnimal()
Hi Sandeep,
In Java, Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.
Does the same way is possible in Python ?
Upvote ShareYes, Dhirendra.
You are right the same concept is there in Python too.
We do that by using the __init__ function and calling it.
The self keyword is used to point that object.
All the best. Happy Learning and coding!
Upvote Shareerror : 500 : Internal Server Error
in jupyter
Upvote Sharelogout and reconnect again. or stop and restart server
Upvote Share