Class 1
Class 1
What is an object?
An object is created using the constructor of the class. This object will
then be called the instance of the class. In Python we create instances
in the following manner
Instance = class(arguments) -->
class Student():
# Class attribute (shared by all instances of the class)
collage_name = "Bahria Collage"
name = "Zubair" # class attribute (this is not used inside
__init__)
Constructor in Python:
In Python, the constructor method is named init(). It is
called automatically when you create a new object from a
class. You can pass arguments to the constructor to
initialize object-specific values.
Example:
class Person:
def __init__(self, name, age):
# This is the constructor
self.name = name # Initializing object attribute 'name'
self.age = age # Initializing object attribute 'age'
print(s1.get_grade()) # Output: A+
def average(self):
return (self.math + self.physics + self.english) / 3
def pass_fail(self):
if self.average() >= 70:
return "Pass"
else:
return "Fail"
print(f"\nAverage::{std1.average()},Pass/Fail::{std1.pass_fail()}")
Average::75.0,Pass/Fail::Pass
Static Method
A static method in Python is a method defined within a
class that doesn’t require access to the instance (object) or
class itself. It behaves like a regular function but belongs
to the class’s namespace. You can call it on the class itself
or on instances of the class, and it doesn’t take self or cls
as its first parameter.
Incorrect use of static method in your case:
class Student():
def __init__(self, name, math: int, physics: int, english: int):
self.name = name
self.math = math
self.physics = physics
self.english = english
@staticmethod
def average():
# This will raise an error because static methods can't access
self.math, self.physics, etc.
return (self.math + self.physics + self.english) / 3
def pass_fail(self):
if self.average() >= 70:
return "Pass"
else:
return "Fail"
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Cell In[30], line 21
17 return "Fail"
20 std1 = Student("Sohail", 60, 79, 86)
---> 21 print(f"Average::{std1.average()}")
@staticmethod
def average(math, physics, english):
return (math + physics + english) / 3
def pass_fail(self):
if self.average(self.math, self.physics, self.english) >= 70:
return "Pass"
else:
return "Fail"
False