What is a class ?
Class is way to represent Object found in the Real World.The way we define a function using the keyword def ,class can be created using the keyword class.
So Lets create a class which describes the behavior of a human being using a Human class.
Syntax
class Human(object):
As humans we have a name & age these are attributes.
Now let create a class Human with name & age.To represent the behavior of the Human we have defined two method eat() & my_stomach().
human.py
With human.py we have create a human class ie... we have a blueprint for Humans
Function within a class are known as methods
Now lets create a who Human whose name is Jude Augustine,age 24 from the Human class ie... we are creating an object whose name is Jude Augustine & age 24
object.py
lets run object.py
__init__()--- is used to assign value to the object ie..initialize the attributes.
The INIT method doesn't have a return statement, but it return the object that was created.
__str__()--- it return information about the object.
Lets us talk to Jude why is he so sad.
Let write code it and save it in conversation1.py
Lets make Jude Happy....
Lets write the code for the above and save in conversation2.py
Creating Multiple Objects from Human Class
Create James & John whose ages are 21 &22 have a sister whose name is Lisa who is 18 year Old,letscreate them using the Human Class.
family.py
save the above code in family.py & run it
#1 in family.py we are importing the Human class from the file human.py
#2 we create a brother_james with name james & age 21.
#3 we create a brother_john which is an object of class Human with name John & is 22 years old.
Creating multiple objects using List-Comprehension
from the above code we notice that humans[0] ----> James,24
humans[1] ----> John,22
humans[2] ----> Lisa,18
Now lets test human.py using Unittest module
Lets now write the code for the above test cases.
testHuman.py
Now lets run it testHuman.py
Now lets write some negative test cases
TookKIT
Human Class with few TookkIT elements.
1)Instance Variables are defined within the __init__ ()--method.
Information about Instance variable may vary as we can see from the multiple objects code.
Eg for Human class , name & age are instance variables.
2)Regular methods----function within a class are know are methods
Eg---- __init__(), __str__() ,eat() , my_stomach() are all methods
all the above method use self ,ie method using self are a parameter are known as Regular Methods.
3)Class Variables--- as human being we all have a heart & every being has One Heart.
Eg-- heart = 14)Static Methods-- method that dont need self as a paramter, because they dont modify the Instance variables.They are helper function which can be used by other Regular Method.
They are added to class using decorators.
Eg @staticmethod
def heart_sound():
print("lup--dup--lup---dup")
How does you heartBeat
the code for the above scenario
heart.pyRun it
No comments:
Post a Comment