Wednesday, May 17, 2023

#PYTHON(DAY21)instance,static attributes and methods

 

#PYTHON(DAY21)

instance attributes

  • object level attribute
  • these may or may not have the same values across all objects
  • in above example, the crust,oil etc can have different values for different objects, these can be considered as instance attributes
class Foo:
def __init__(self, a, b):
self.a = a
self.b = b
x1,x2 = Foo(10,20), Foo(11,22)
print((x1.a,x1.b), (x2.a,x2.b), sep = '\n')

And the output is:

(10, 20)
(11, 22)

static attributes

  • static variable remains common for the entire class
  • the user can change according to his requirement
class Rest:
disc = 0
def __init__(self,bill):
self.bill = bill


def totalBill(self):
return self.bill-(self.bill*self.disc)
a1 = Rest(50)
print(a1.totalBill())

a2 = Rest(50)
a2.disc = 0.10
a2.totalBill()

And the output is:

50
45.0

methods

instance methods

  • these methods take self as first parameter, we use these methods to modify or alter the instance’s attributes or state
  • in dictionary from keys is a class method and all are instance methods.
  • instance method acts on object, attributes changes on object level

class methods

  • these methods accepts ‘cls’ as their first attribute, we define a class method by using a decorator @classmethod
  • class method acts on class level
  • using class method we can alter class attributes

static methods

  • we define static methods using @staticmethod decorator, these methods accept no cls or self as first parameter
  • it does not work on class or object
class Rest:
disc = 0
def __init__(self,bill):
self.bill = bill

def printBill(self):
print(f'bill before discount is {self.bill}')

@classmethod
def discount(cls):
print(f'the discount you availed is{cls.disc} %')
#print(f'total bill to paidmpost discount is {self.})
@staticmethod
def greet():
print('welcome')
Rest.discount()

# using the object
a1 = Rest(50)
a1.printBill()
a1.discount() # we can also access class attribute by using object without self

And the output is:

the discount you availed is0 %
bill before discount is 50
the discount you availed is0 %
a1.greet()
Rest.greet()

And the output is:

welcome
welcome
class student1():
y = 60
def details(self,name,rollno,study,sec,totalmarks):
self.n = name
self.r = rollno
self.a = study
self.sec = sec
self.m = totalmarks

def cutoff(self):
if self.m>=self.y:
print('pass')
else:
print('fail')
def over(self):
print((f'''student name is {self.n} rollno:{self.r} belongs to {self.a}class section {self.sec} total marks are {self.m}'''))
ab = student1()
ab.details('xyz',456,7,'a',50)
ab.cutoff()
ab.over()
fail
student name is xyz rollno:456 belongs to 7class section a total marks are 50

No comments:

Post a Comment

Building Static Website(part6) HTML Lists

  Building Static Website (part6) HTML Lists Today, let us add some lists to our detailed view section by using html lists. Lists: List is a...