Foundations of Python

You are currently auditing this course.
128 / 134

Python Classes and Objects

Overview

As part of this session, we will learn the following:

  1. What is a Class?
  2. What are objects?
  3. What are the methods and attributes?
  4. A simple example of a class in Python
  5. dir() and type() functions
  6. Using the dir() function on strings
  7. Object Lifecycle
  8. What are constructors in a Class?
  9. What is Inheritance?
  10. How do we inherit a class in Python?

Recording of Session


Slides

Code Repository for the course on GitHub


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)

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: 

I am constructor  # This is okay
I am destructor  # why this is called?
I am constructor of class 2 # This is okay
I am destructor # why this is called?
36 # This is okay
I am insidefunction of class2 # This is okay
16   # If destructor is called that means object is deleted? then why I am able to use Obj1 again
  Upvote    Share

Let’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 of CalculationE is called, printing: 'I am constructor'.

2. Destructor Call (__del__):

After the constructor runs, Python's garbage collector may call the destructor __del__ for obj1, even if obj1 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 of inher_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__ for obj2, 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 obj2.multy_fun(6,6) is called, it uses the method from the parent class CalculationE, which multiplies the two numbers and prints '36'.

  Upvote    Share

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 why obj1.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    Share

Then what is the use of destructor? If I am not creatining destructor then garbage collector will automatically clean the memory.

  Upvote    Share

You'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:

class FileHandler:
    def __init__(self, file_path):
        self.file = open(file_path, 'w')
    
    def write_data(self, data):
        self.file.write(data)
    
    def __del__(self):
        self.file.close()  # Ensures the file is closed when the object is destroyed
        print("File closed")

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:

class Logger:
    def __del__(self):
        print("Object is being destroyed, logging shutdown")

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:

class Resource:
    def __enter__(self):
        print("Acquiring resource")
        return self
    
    def __exit__(self, exc_type, exc_value, traceback):
        print("Releasing resource")

with Resource() as r:
    print("Using resource")


#Output:-
Acquiring resource
Using resource
Releasing resource

The __exit__ method (similar to a destructor in this context) ensures that resources are properly released when the block finishes, even if an exception occurs.

  Upvote    Share

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    Share

The 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    Share

Can you share the code snippets of both the ways along with the error?

  Upvote    Share
class cat:
    def _init_(self,color,size):
        self.color = color
        self.size = size
    def func():
        print ("Color is",self.color)
        print ("Size is",self.size)
cat1 = cat("Brown",25)
cat1.func()
TypeError                                 Traceback (most recent call last)
<ipython-input-1-8bd757ca2c7a> in <module>
      6         print ("Color is",self.color)
      7         print ("Size is",self.size)
----> 8 cat1 = cat("Brown",25)
      9 cat1.func()
     10 

TypeError: object() takes no parameters
  Upvote    Share
class cat:
    def _init_(self,color,size):
        self.color = color
        self.size = size
    def func(self):
        print ("Color is",self.color)
        print ("Size is",self.size)
cat1 = cat()
cat1._init_("Brown",25)
cat1.func()
        
Color is Brown
Size is 25
  Upvote    Share

Let'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 (__init__ method) is automatically called to initialize the object. If you define __init__ to accept certain arguments (like color and size), you need to provide these arguments when creating an instance of the class.

 1  Upvote    Share

Thanks a lot for the clarifcation!

 

  Upvote    Share

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.

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-50-05ef88fee5a8> in <module>
----> 1 from my_lib import interest, compoundinterest
      2 from my_lib import *

ImportError: cannot import name 'interest'
  Upvote    Share

file location: 

/home/arunchaluvadhi1424/ml/python
  Upvote    Share

This comment has been removed.

Please make sure there exists a function with the same name.

  Upvote    Share

is there any main method in python using class??

  Upvote    Share

Hi,

Can you further ellaborate your question?

  Upvote    Share

At 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    Share

Hi,

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    Share

Sir,

 

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    Share

Hi,

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    Share

Its giving me error while imprting from mylib.py

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-da8fe716aed1> in <module>
----> 1 mylib.compoundinterest(100,5,2)

AttributeError: module 'mylib' has no attribute 'compoundinterest'
  Upvote    Share

Hi,

Makesure there exists module named mylib, and that there is a function called compoundinterest  inside that.

Thanks.

  Upvote    Share

Sir,

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    Share

Hi,

You can call the destructor explicitely by using the following command:

del obj

The desctructor is also called when an object goes out of reference or when the program ends.

Thanks.

  Upvote    Share

Sir,
The 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' ??

  Upvote    Share

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    Share

Thank You for the reply, Sir. I will look into it.

  Upvote    Share

Hi 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    Share

Hi,

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    Share

Hi Team,

I am not clear about packages, as i didn't find any practical in vedio, please assist.

  Upvote    Share

Hi 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    Share

Hi,

__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    Share

I am getting this Error again and again after changing the text file name also. pls help me what is issue in this?

  Upvote    Share

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    Share

file 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 .

  Upvote    Share

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    Share

This part is covered in modules at the end of video.

  Upvote    Share

Hi, 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:

cat: mylib.py: No such file or directory

*************************************************************************

  Upvote    Share

Hi,

The file "mylib.py" should exist so that we could import it. So make sure it exists.

Thanks.

  Upvote    Share

Hi,

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: 

10.25

**********************************************************************

  Upvote    Share

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    Share

Hi,

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    Share

Hi,

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    Share

Great.....Thanks !!!

  Upvote    Share
When I type the exact code for class PartyAnimal (described at 18:00 onwards) I get this error. Could you please help me?
TypeError                                 Traceback (most recent call last)
<ipython-input-24-a9723f711cf4> in <module>
     10         print(self.nam,'So far',self.x)
     11 #object or class of our own
---> 12 s = PartyAnimal("Sally")
     13 s.party()
     14 #an.party()

TypeError: object() takes no parameters
  Upvote    Share

Hi Bhaswati,

Can you please check the code again? if you're not able to find the error please post screenshot of full code.

  Upvote    Share

In the method within the class definition:

def party(self) : 
 self.x = self.x + 1 
 print("So far",self.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    Share

Hi,

x is an attribute of the class. So, self.x means the attribute x of the class object.

Thanks.

  Upvote    Share

Pl help to fix this problem

  Upvote    Share

Hi,

Could you please tell us what is the issue you are facing, also share a screenshot of the same if possible.

Thanks.

  Upvote    Share

 There 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? 

 

 

  Upvote    Share

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    Share

This 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    Share

Hi,

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    Share

How to import a module that exists in a location other than the current directory?

 1  Upvote    Share

Hi,

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    Share

I 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

10

-------------

emp_pro.__name

Out Put Error:
AttributeError                            Traceback (most recent call last)
<ipython-input-55-78824936777c> in <module>
----> 1 emp_pro.__name

AttributeError: 'employee_private' object has no attribute '__name'

----------------

emp_pro.getName()

Out Put: 'Madhu'

  Upvote    Share

Hi,

Are you facing any challenges?

Thanks.

  Upvote    Share

This comment has been removed.

       The destructor is showing its value as 2 in both the instances. How can i rectify this ?          

 

  Upvote    Share

Hi,

This is because you are calling it twice. Could you try the following:

an = PartyAnimal()
an.party()

Thanks.

  Upvote    Share

           its showing the value of destructor as 1 now 

  Upvote    Share

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    Share

This comment has been removed.

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-13150f85e08c> in <module>
      1 # Check function
----> 2 my_lib.compoundinterest(100, 5, 2)

NameError: name 'my_lib' is not defined
  Upvote    Share

Hi,

Could you please tell me this is a part of which assessment?

Thanks.

  Upvote    Share

This 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

  Upvote    Share

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    Share

Hi 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?

  Upvote    Share

Hi,

Could you try creating one instance of the class and try again? It is working fine on my end.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hi Rajtilak, It does not seem to work. Even in the recording from Sandeep has the same issue.

  Upvote    Share

Sir,
Can the first argument be anything in place of self in the constructor function definition like other function definition in C language.

  Upvote    Share

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    Share

Hi 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    Share

Hi,

Please let us know if you are still facing this issue.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

So, self here basically acts like the 'this' keyword of C++
does,
self.attribute (in Python) equivalent to this->attribute (in C++)
?

  Upvote    Share

Hi,

Yes, self is the equivalent of this of C++ in many respect.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hi 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    Share

Hi, 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    Share

Hi Sandeep/CloudXlabs,
if 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?

  Upvote    Share

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    Share

What is the name of the book mentioned in this video when Sandeep was talking about the mathematics behind machine learning?

  Upvote    Share

#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    Share

Please 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()
an.party()
an.party()
an.party()
so=partyAnimal()

  Upvote    Share

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    Share

Yes, 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    Share

error : 500 : Internal Server Error

in jupyter

  Upvote    Share

logout and reconnect again. or stop and restart server

  Upvote    Share