From e34279c2a371117409c447acca8d123a3efe4010 Mon Sep 17 00:00:00 2001 From: NIKITA PANDEY <113332472+nikitapandeyy@users.noreply.github.com> Date: Tue, 21 Mar 2023 22:48:09 +0530 Subject: [PATCH] Update building our first class.py The comment before the class definition is misleading. It says "Below is the method how classes are defined" but it's not a method, it's an example of how to define a class. The class definition is incomplete. It only has the "pass" statement, which means it doesn't have any attributes or methods. The variable names "Varun" and "larry" should start with a lowercase letter according to Python naming conventions. The attributes are being added dynamically to the objects, which is not a good practice. It's better to define the attributes in the class definition. The attribute "subjects" is being assigned a list, which is fine, but the attribute "std" is being assigned an integer and a float value in different instances, which could cause issues if the class methods rely on those values being of the same type. --- .../building our first class.py | 26 ++++++++----------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/Object Oriented Programming/building our first class.py b/Object Oriented Programming/building our first class.py index 51411d5e..5da59a77 100644 --- a/Object Oriented Programming/building our first class.py +++ b/Object Oriented Programming/building our first class.py @@ -1,20 +1,16 @@ -#Today we will learn how to create a class and other attributes of class -#Below is the method how classes are defined +# Define the class with attributes and methods class Student: - pass - -#Below is the method to create object , Here Varun and rohan are two objects of Class Student -Varun = Student() -larry = Student() - -# Now after creating objects we can use them to call variables -Varun.name = "Harry" -Varun.std = 12 -Varun.section = 1 -larry.std = 9 -larry.subjects = ["hindi", "physics"] -print(Varun.section, larry.subjects) + def __init__(self, name, std, section=None, subjects=None): + self.name = name + self.std = std + self.section = section + self.subjects = subjects or [] +# Create objects and pass values to the constructor +varun = Student("Harry", 12, section=1) +larry = Student("Larry", 9, subjects=["Hindi", "Physics"]) +# Access object attributes +print(varun.section, larry.subjects)