Module-5 Classes and Objects DEPARTMENT OF MECHANICAL ENGINEERING MAHARAJA INSTITUTE OF TECHNOLOGY MYSORE By: Prof.Yogesh Kumar K J Assistant Professor
Overview A class in python is the blueprint from which specific objects are created. It lets you structure your software in a particular way. Here comes a question how? Classes allow us to logically group our data and function in a way that it is easy to reuse and a way to build upon if need to be. Consider the below image. (a) (b)
Overview In the first image (a), it represents a blueprint of a house that can be considered as Class. With the same blueprint, we can create several houses and these can be considered as Objects. Using a class, you can add consistency to your programs so that they can be used in cleaner and efficient ways. The attributes are data members (class variables and instance variables) and methods which are accessed via dot notation.  Class variable is a variable that is shared by all the different objects/instances of a class.  Instance variables are variables which are unique to each instance. It is defined inside a method and belongs only to the current instance of a class.  Methods are also called as functions which are defined in a class and describes the behaviour of an object.
Overview Now, let us move ahead and see how it works in Spyder. To get started, first have a look at the syntax of a python class Syntax: class Class_name: statement-1 . . statement-N Here, the “class” statement creates a new class definition.The name of the class immediately follows the keyword “class” in python which is followed by a colon.
To create a class in python, consider the below example: class student: pass #no attributes and methods s_1=student() s_2=student() #instance variable can be created manually s_1.first="yogesh" s_1.last="kumar" s_1.email="yogesh@gmail.co" s_1.age=35 s_2.first="anil" s_2.last="kumar" s_2.email="anil@yahoo.com" s_2.age=36 print(s_1.email) print(s_2.email) Output: yogesh@gmail.co anil@yahoo.com Now, what if we don’t want to manually set these variables. You will see a lot of code and also it is prone to error. So to make it automatic, we can use “init” method. For that, let’s understand what exactly are methods and attributes in a python class.
Methods and Attributes in a Python Class Creating a class is incomplete without some functionality. So functionalities can be defined by setting various attributes which acts as a container for data and functions related to those attributes. Functions in python are also called as Methods. init method, it is a special function which gets called whenever a new object of that class is instantiated.You can think of it as initialize method or you can consider this as constructors if you’re coming from any another object-oriented programming background such as C++, Java etc. Now when we set a method inside a class, they receive instance automatically. Let’s go ahead with python class and accept the first name, last name and fees using this method.
class student: def __init__(self, first, last, fee): self.fname=first self.lname=last self.fee=fee self.email=first + "." + last + "@yahoo.com" s_1=student("yogesh","kumar",75000) s_2=student("anil","kumar",100000) print(s_1.email) print(s_2.email) print(s_1.fee) print(s_2.fee) Output: yogesh.kumar@yahoo.com anil.kumar@yahoo.com 75000 100000 “init” method, we have set these instance variables (self, first, last, fee). Self is the instance which means whenever we write self.fname=first, it is same as s_1.first=’yogesh’. Then we have created instances of employee class where we can pass the values specified in the init method. This method takes the instances as arguments. Instead of doing it manually, it will be done automatically now. Methods and Attributes in a Python Class
Next, we want the ability to perform some kind of action. For that, we will add a method to this class. Suppose I want the functionality to display the full name of the employee. So let’s us implement this practically class student: def __init__(self, first, last, fee): self.fname=first self.lname=last self.fee=fee self.email=first + "." + last + "@yahoo.com" def fullname(self): return '{}{}'.format(self.fname,self.lname) s_1=student("yogesh", "kumar", 75000) s_2=student("anil", "kumar", 100000) print(s_1.email) print(s_2.email) print(s_1.fullname()) print(s_2.fullname()) Output: yogesh.kumar@yahoo.com anil.kumar@yahoo.com yogeshkumar anilkumar As you can see above, we have created a method called “full name” within a class. So each method inside a python class automatically takes the instance as the first argument. Now within this method, we have written the logic to print full name and return this instead of s_1 first name and last name. Next, we have used “self” so that it will work with all the instances. Therefore to print this every time, we use a method. Methods and Attributes in a Python Class
Moving ahead with Python classes, there are variables which are shared among all the instances of a class. These are called as class variables. Instance variables can be unique for each instance like names, email, fee etc. Complicated? Let’s understand this with an example. Refer the code below to find out the annual rise in the fee. class student: perc_raise =1.05 def __init__(self, first, last, fee): self.fname=first self.lname=last self.fee=fee self.email=first + "." + last + "@yahoo.com" def fullname(self): return "{}{}".format(self.fname,self.lname) def apply_raise(self): self.fee=int(self.fee*1.05) s_1=student("yogesh","kumar",350000) s_2=student("anil","kumar",100000) print(s_1.fee) s_1.apply_raise() print(s_1.fee) Output: 350000 367500 As you can see above, we have printed the fees first and then applied the 1.5% increase. In order to access these class variables, we either need to access them through the class or an instance of the class. Methods and Attributes in a Python Class
Attributes in a Python Class Attributes in Python defines a property of an object, element or a file. There are two types of attributes: Built-in Class Attributes: There are various built-in attributes present inside Python classes. For example _dict_, _doc_, _name _, etc. Let us take the same example where we want to view all the key- value pairs of student1. For that, we can simply write the below statement which contains the class namespace: print(s_1.__dict__) After executing it, you will get output such as: {‘fname’:‘yogesh’,‘lname’:‘kumar’,‘fee’: 350000, ’email’: ‘yogesh.kumar@yahoo.com’}
Attributes defined by Users: Attributes are created inside the class definition. We can dynamically create new attributes for existing instances of a class. Attributes can be bound to class names as well. Next, we have public, protected and private attributes. Let’s understand them in detail: Naming Type Meaning Name Public These attributes can be freely used inside or outside of a class definition _name Protected Protected attributes should not be used outside of the class definition, unless inside of a subclass definition __name Private This kind of attribute is inaccessible and invisible. It’s neither possible to read nor to write those attributes, except inside of the class definition itself Next, let’s understand the most important component in a python class i.e Objects. Attributes in a Python Class
What are objects in a Python Class? As we have discussed above, an object can be used to access different attributes. It is used to create an instance of the class. An instance is an object of a class created at run-time. To give you a quick overview, an object basically is everything you see around. For eg: A dog is an object of the animal class, I am an object of the human class. Similarly, there can be different objects to the same phone class. This is quite similar to a function call which we have already discussed.
Objects in a Python class MyClass: def func(self): print('Hello') # create a new MyClass ob = MyClass() ob.func()
Programmer-defined types We have many of Python’s built-in types; now we are going to define a new type. As an example, we will create a type called Point that represents a point in two-dimensional space. (0, 0) represents the origin, and (x, y) represents the point x units to the right and y units up from the origin. A programmer-defined type is also called a class. A class definition looks like this: class Point: """Represents a point in 2-D space.""" The header indicates that the new class is called Point.The body is a docstring (documentation strings) that explains what the class is for. Defining a class named Point creates a class object. >>> Point <class ' main .Point'> Because Point is defined at the top level, its “full name” is main .Point.The class object is like a factory for creating objects.To create a Point, we call Point as if it were a function.
Point >>> blank = Point() >>> blank < main .Point object at 0xb7e9d3ac>  The return value is a reference to a Point object, which we assign to blank. Creating a new object is called instantiation, and the object is an instance of the class.  When we print an instance, Python tells you what class it belongs to and where it is stored in  memory.  Every object is an instance of some class, so “object” and “instance” are interchangeable.  But in this chapter I use “instance” to indicate that I am talking about a programmer defined type.
Attributes We can assign values to an instance using dot notation: >>> blank.x = 3.0 >>> blank.y = 4.0 In this case, though, we are assigning values to named elements of an object.These elements are called attributes. The variable blank refers to a Point object, which contains two attributes. Each attribute refers to a floating-point number.We can read the value of an attribute using the same syntax: >>> blank.y 4.0 >>> x = blank.x >>> x 3.0 The expression blank.x means, “Go to the object blank refers to and get the value of x.” In the example, we assign that value to a variable named x. There is no conflict between the variable x and the attribute x.You can use dot notation as part of any expression.
Overview For example: >>> '(%g, %g)' % (blank.x, blank.y) '(3.0, 4.0)' >>> distance = math.sqrt(blank.x**2 + blank.y**2) >>> distance 5.0
Rectangles  We are designing a class to represent rectangles.There are at least two possibilities  You could specify one corner of the rectangle (or the center), the width, and the height  You could specify two opposing corners. At this point it is hard to say whether either is better than the other, so we’ll implement the first one, just as an example. Here is the class definition: class Rectangle: """Represents a rectangle. attributes: width, height, corner. """
Rectangle The expression box.corner.x means, “Go to the object box refers to and select the attribute named corner; then go to that object and select the attribute named x.” The docstring lists the attributes: width and height are numbers; corner is a Point object that specifies the lower-left corner. To represent a rectangle, we have to instantiate a Rectangle object and assign values to the attributes: box = Rectangle( ) box.width = 100.0 box.height = 200.0 box.corner = Point( ) box.corner.x = 0.0 box.corner.y = 0.0 An object that is an attribute of another object is embedded.
Overview
Overview
Overview
Overview
Overview
Overview

Module-5-Classes and Objects for Python Programming.pptx

  • 1.
    Module-5 Classes and Objects DEPARTMENTOF MECHANICAL ENGINEERING MAHARAJA INSTITUTE OF TECHNOLOGY MYSORE By: Prof.Yogesh Kumar K J Assistant Professor
  • 2.
    Overview A class inpython is the blueprint from which specific objects are created. It lets you structure your software in a particular way. Here comes a question how? Classes allow us to logically group our data and function in a way that it is easy to reuse and a way to build upon if need to be. Consider the below image. (a) (b)
  • 3.
    Overview In the firstimage (a), it represents a blueprint of a house that can be considered as Class. With the same blueprint, we can create several houses and these can be considered as Objects. Using a class, you can add consistency to your programs so that they can be used in cleaner and efficient ways. The attributes are data members (class variables and instance variables) and methods which are accessed via dot notation.  Class variable is a variable that is shared by all the different objects/instances of a class.  Instance variables are variables which are unique to each instance. It is defined inside a method and belongs only to the current instance of a class.  Methods are also called as functions which are defined in a class and describes the behaviour of an object.
  • 4.
    Overview Now, let usmove ahead and see how it works in Spyder. To get started, first have a look at the syntax of a python class Syntax: class Class_name: statement-1 . . statement-N Here, the “class” statement creates a new class definition.The name of the class immediately follows the keyword “class” in python which is followed by a colon.
  • 5.
    To create aclass in python, consider the below example: class student: pass #no attributes and methods s_1=student() s_2=student() #instance variable can be created manually s_1.first="yogesh" s_1.last="kumar" s_1.email="yogesh@gmail.co" s_1.age=35 s_2.first="anil" s_2.last="kumar" s_2.email="anil@yahoo.com" s_2.age=36 print(s_1.email) print(s_2.email) Output: yogesh@gmail.co anil@yahoo.com Now, what if we don’t want to manually set these variables. You will see a lot of code and also it is prone to error. So to make it automatic, we can use “init” method. For that, let’s understand what exactly are methods and attributes in a python class.
  • 6.
    Methods and Attributesin a Python Class Creating a class is incomplete without some functionality. So functionalities can be defined by setting various attributes which acts as a container for data and functions related to those attributes. Functions in python are also called as Methods. init method, it is a special function which gets called whenever a new object of that class is instantiated.You can think of it as initialize method or you can consider this as constructors if you’re coming from any another object-oriented programming background such as C++, Java etc. Now when we set a method inside a class, they receive instance automatically. Let’s go ahead with python class and accept the first name, last name and fees using this method.
  • 7.
    class student: def __init__(self,first, last, fee): self.fname=first self.lname=last self.fee=fee self.email=first + "." + last + "@yahoo.com" s_1=student("yogesh","kumar",75000) s_2=student("anil","kumar",100000) print(s_1.email) print(s_2.email) print(s_1.fee) print(s_2.fee) Output: yogesh.kumar@yahoo.com anil.kumar@yahoo.com 75000 100000 “init” method, we have set these instance variables (self, first, last, fee). Self is the instance which means whenever we write self.fname=first, it is same as s_1.first=’yogesh’. Then we have created instances of employee class where we can pass the values specified in the init method. This method takes the instances as arguments. Instead of doing it manually, it will be done automatically now. Methods and Attributes in a Python Class
  • 8.
    Next, we wantthe ability to perform some kind of action. For that, we will add a method to this class. Suppose I want the functionality to display the full name of the employee. So let’s us implement this practically class student: def __init__(self, first, last, fee): self.fname=first self.lname=last self.fee=fee self.email=first + "." + last + "@yahoo.com" def fullname(self): return '{}{}'.format(self.fname,self.lname) s_1=student("yogesh", "kumar", 75000) s_2=student("anil", "kumar", 100000) print(s_1.email) print(s_2.email) print(s_1.fullname()) print(s_2.fullname()) Output: yogesh.kumar@yahoo.com anil.kumar@yahoo.com yogeshkumar anilkumar As you can see above, we have created a method called “full name” within a class. So each method inside a python class automatically takes the instance as the first argument. Now within this method, we have written the logic to print full name and return this instead of s_1 first name and last name. Next, we have used “self” so that it will work with all the instances. Therefore to print this every time, we use a method. Methods and Attributes in a Python Class
  • 9.
    Moving ahead withPython classes, there are variables which are shared among all the instances of a class. These are called as class variables. Instance variables can be unique for each instance like names, email, fee etc. Complicated? Let’s understand this with an example. Refer the code below to find out the annual rise in the fee. class student: perc_raise =1.05 def __init__(self, first, last, fee): self.fname=first self.lname=last self.fee=fee self.email=first + "." + last + "@yahoo.com" def fullname(self): return "{}{}".format(self.fname,self.lname) def apply_raise(self): self.fee=int(self.fee*1.05) s_1=student("yogesh","kumar",350000) s_2=student("anil","kumar",100000) print(s_1.fee) s_1.apply_raise() print(s_1.fee) Output: 350000 367500 As you can see above, we have printed the fees first and then applied the 1.5% increase. In order to access these class variables, we either need to access them through the class or an instance of the class. Methods and Attributes in a Python Class
  • 10.
    Attributes in aPython Class Attributes in Python defines a property of an object, element or a file. There are two types of attributes: Built-in Class Attributes: There are various built-in attributes present inside Python classes. For example _dict_, _doc_, _name _, etc. Let us take the same example where we want to view all the key- value pairs of student1. For that, we can simply write the below statement which contains the class namespace: print(s_1.__dict__) After executing it, you will get output such as: {‘fname’:‘yogesh’,‘lname’:‘kumar’,‘fee’: 350000, ’email’: ‘yogesh.kumar@yahoo.com’}
  • 11.
    Attributes defined byUsers: Attributes are created inside the class definition. We can dynamically create new attributes for existing instances of a class. Attributes can be bound to class names as well. Next, we have public, protected and private attributes. Let’s understand them in detail: Naming Type Meaning Name Public These attributes can be freely used inside or outside of a class definition _name Protected Protected attributes should not be used outside of the class definition, unless inside of a subclass definition __name Private This kind of attribute is inaccessible and invisible. It’s neither possible to read nor to write those attributes, except inside of the class definition itself Next, let’s understand the most important component in a python class i.e Objects. Attributes in a Python Class
  • 12.
    What are objectsin a Python Class? As we have discussed above, an object can be used to access different attributes. It is used to create an instance of the class. An instance is an object of a class created at run-time. To give you a quick overview, an object basically is everything you see around. For eg: A dog is an object of the animal class, I am an object of the human class. Similarly, there can be different objects to the same phone class. This is quite similar to a function call which we have already discussed.
  • 13.
    Objects in aPython class MyClass: def func(self): print('Hello') # create a new MyClass ob = MyClass() ob.func()
  • 14.
    Programmer-defined types We havemany of Python’s built-in types; now we are going to define a new type. As an example, we will create a type called Point that represents a point in two-dimensional space. (0, 0) represents the origin, and (x, y) represents the point x units to the right and y units up from the origin. A programmer-defined type is also called a class. A class definition looks like this: class Point: """Represents a point in 2-D space.""" The header indicates that the new class is called Point.The body is a docstring (documentation strings) that explains what the class is for. Defining a class named Point creates a class object. >>> Point <class ' main .Point'> Because Point is defined at the top level, its “full name” is main .Point.The class object is like a factory for creating objects.To create a Point, we call Point as if it were a function.
  • 15.
    Point >>> blank =Point() >>> blank < main .Point object at 0xb7e9d3ac>  The return value is a reference to a Point object, which we assign to blank. Creating a new object is called instantiation, and the object is an instance of the class.  When we print an instance, Python tells you what class it belongs to and where it is stored in  memory.  Every object is an instance of some class, so “object” and “instance” are interchangeable.  But in this chapter I use “instance” to indicate that I am talking about a programmer defined type.
  • 16.
    Attributes We can assignvalues to an instance using dot notation: >>> blank.x = 3.0 >>> blank.y = 4.0 In this case, though, we are assigning values to named elements of an object.These elements are called attributes. The variable blank refers to a Point object, which contains two attributes. Each attribute refers to a floating-point number.We can read the value of an attribute using the same syntax: >>> blank.y 4.0 >>> x = blank.x >>> x 3.0 The expression blank.x means, “Go to the object blank refers to and get the value of x.” In the example, we assign that value to a variable named x. There is no conflict between the variable x and the attribute x.You can use dot notation as part of any expression.
  • 17.
    Overview For example: >>> '(%g,%g)' % (blank.x, blank.y) '(3.0, 4.0)' >>> distance = math.sqrt(blank.x**2 + blank.y**2) >>> distance 5.0
  • 18.
    Rectangles  We aredesigning a class to represent rectangles.There are at least two possibilities  You could specify one corner of the rectangle (or the center), the width, and the height  You could specify two opposing corners. At this point it is hard to say whether either is better than the other, so we’ll implement the first one, just as an example. Here is the class definition: class Rectangle: """Represents a rectangle. attributes: width, height, corner. """
  • 19.
    Rectangle The expression box.corner.xmeans, “Go to the object box refers to and select the attribute named corner; then go to that object and select the attribute named x.” The docstring lists the attributes: width and height are numbers; corner is a Point object that specifies the lower-left corner. To represent a rectangle, we have to instantiate a Rectangle object and assign values to the attributes: box = Rectangle( ) box.width = 100.0 box.height = 200.0 box.corner = Point( ) box.corner.x = 0.0 box.corner.y = 0.0 An object that is an attribute of another object is embedded.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.