Python is an object-oriented programming language. Python Classes and Objects are the core building blocks of Python programming language. Show
Python ClassBy this time, all of you should have already learned about Python Data Types. If you remember, basic data types in python refer to only one kind of data at a time. How would it be if you could declare a data type which itself contains more than one data types and can work with them with the help of any function? Python class gives you that opportunity. Python class is the blueprint on which instances of the class are created. Simple Python Class DeclarationHere’s the very basic structure of python class definition. class ClassName: # list of python class variables # python class constructor # python class method definitionsNow, let’s work with real examples. #definition of the class starts here class Person: #initializing the variables name = "" age = 0 #defining constructor def __init__(self, personName, personAge): self.name = personName self.age = personAge #defining class methods def showName(self): print(self.name) def showAge(self): print(self.age) #end of the class definition # Create an object of the class person1 = Person("John", 23) #Create another object of the same class person2 = Person("Anne", 102) #call member methods of the objects person1.showAge() person2.showName()This example is pretty much self-explanatory. As we know, the lines starting with “#” are python comments. The comments explain the next executable steps. This code produces the following output. Python Class Definitionclass Person:This line marks the beginning of class definition for class ‘Person’. Python Class Variables#initializing the variables name = "" age = 0‘name’ and ‘age’ are two member variables of the class ‘Person’. Every time we declare an object of this class, it will contain these two variables as its member. This part is optional as they can be initialized by the constructor. Python Class Constructor#defining constructor def __init__(self, personName, personAge): self.name = personName self.age = personAgePython class constructor is the first piece of code to be executed when you create a new object of a class. Primarily, the constructor can be used to put values in the member variables. You may also print messages in the constructor to be confirmed whether the object has been created. We shall learn a greater role of constructor once we get to know about python inheritance. The constructor method starts with def __init__. Afterward, the first parameter must be ‘self’, as it passes a reference to the instance of the class itself. You can also add additional parameters like the way it is shown in the example. ‘personName’ and ‘personAge’ are two parameters to sent when a new object is to be created. Python Class Methods#defining python class methods def showName(self): print(self.name)Methods are declared in the following way: def method_name(self, parameter 1, parameter 2, …….) statements…….. return value (if required)In the pre-stated example, we’ve seen that the method showName() prints value of ‘name’ of that object. We shall discuss a lot more about python methods some other day. Python Class Object# Create an object of the class person1 = Person("Richard", 23) #Create another object of the same class person2 = Person("Anne", 30) #call member methods of the objects person1.showAge() person2.showName()The way objects are created in python is quite simple. At first, you put the name of the new object which is followed by the assignment operator and the name of the class with parameters (as defined in the constructor). Remember, the number and type of parameters should be compatible with the parameters received in the constructor function. When the object has been created, member methods can be called and member attributes can be accessed (provided they are accessible). #print the name of person1 by directly accessing the ‘name’ attribute print(person1.name)That’s all for the basics of python class. As we are going to learn about python object-oriented features like inheritance, polymorphism in the subsequent tutorials, we shall learn more about python class and its features. Till then, happy coding and good bye! Feel free to comment if you have any query. Reference: Python.org Documentation A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by their class) for modifying their state. To understand the need for creating a class in Python let’s consider an example, let’s say you wanted to track the number of dogs that may have different attributes like breed, and age. If a list is used, the first element could be the dog’s breed while the second element could represent its age. Let’s suppose there are 100 different dogs, then how would you know which element is supposed to be which? What if you wanted to add other properties to these dogs? This lacks organization and it’s the exact need for classes. Syntax: Class Definition class ClassName: # StatementSyntax: Object Definition obj = ClassName() print(obj.atrr)Class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object. Some points on Python class:
Defining a class# Python3 program to # demonstrate defining # a class class Dog: passIn the above example, the class keyword indicates that you are creating a class followed by the name of the class (Dog in this case). Class ObjectsAn Object is an instance of a Class. A class is like a blueprint while an
instance is a copy of the class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven years old. You can have many dogs to create many different instances, but without the class as a guide, you would be lost, not knowing what information is required.
Declaring Objects (Also called instantiating a class)When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances. Example: Declaring an objectPython3class Dog: attr1 = "mammal" attr2 = "dog" def fun(self): print("I'm a", self.attr1) print("I'm a", self.attr2) Rodger = Dog() print(Rodger.attr1) Rodger.fun() Output mammal I'm a mammal I'm a dogIn the above example, an object is created which is basically a dog named Rodger. This class only has two class attributes that tell us that Rodger is a dog and a mammal. The self
When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about. __init__ methodThe __init__ method is similar to constructors in C++ and Java. Constructors are used to initialize the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. It runs as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. Python3class Person: def __init__(self, name): self.name = name def say_hi(self): print('Hello, my name is', self.name) p = Person('Nikhil') p.say_hi() Output: Hello, my name is NikhilClass and Instance VariablesInstance variables are for data, unique to each instance and class variables are for attributes and methods shared by all instances of the class. Instance variables are variables whose value is assigned inside a constructor or method with self whereas class variables are variables whose value is assigned in the class. Defining instance variables using a constructor. Python3class Dog: animal = 'dog' def __init__(self, breed, color): self.breed = breed self.color = color Rodger = Dog("Pug", "brown") Buzo = Dog("Bulldog", "black") print('Rodger details:') print('Rodger is a', Rodger.animal) print('Breed: ', Rodger.breed) print('Color: ', Rodger.color) print('\nBuzo details:') print('Buzo is a', Buzo.animal) print('Breed: ', Buzo.breed) print('Color: ', Buzo.color) print("\nAccessing class variable using class name") print(Dog.animal) Output Rodger details: Rodger is a dog Breed: Pug Color: brown Buzo details: Buzo is a dog Breed: Bulldog Color: black Accessing class variable using class name dogDefining instance variables using the normal method. Python3class Dog: animal = 'dog' def __init__(self, breed): self.breed = breed def setColor(self, color): self.color = color def getColor(self): return self.color Rodger = Dog("pug") Rodger.setColor("brown") print(Rodger.getColor()) Which of the following function is called when a class is used to create a new object?A function like Turtle or Point that creates a new object instance is called a constructor, and every class automatically provides a constructor function which is named the same as the class.
What is the function that gets called when a class is created?The constructor method is a special method of a class for creating and initializing an object instance of that class.
What is the function of class in Python?Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state.
Which method is called when an object is created from a class and allows the class to initialize the attributes of the class?__init__ method
This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.
|