Saturday, 8 May 2021

Class Method Alternative Constructor: OOP Python

# last time we made a program that shows number of leaves, prints objects such as salary, name, and role. This time we want to learn how to take the input as string and split the string into objects properties with a dash.

 

 

class Employee:
    no_of_leaves = 8

    def __init__(self, aname, asalary, arole):
        self.name = aname
        self.salary = asalary
        self.role = arole

    def printdetails(self):
        return f"The Name is {self.name}. Salary is {self.salary} and role is {self.role}"
    
    
    @classmethod
    def change_leaves(cls, newleaves):
        cls.no_of_leaves = newleaves


    @classmethod
    def from_str(cls, string):
        params = string.split("-")
     
        #this is to split the string by hypen and make a list
        #print(params) if you eant to u can print and see how it makes the list
        return cls (params[0], params[1], params[2])
    #this will return the object properties from params list to the Class thats why we used cls command.

    
harry= Employee("harry", "230", "teacher")
rohan= Employee("rohan", "333", "dancer")
karan= Employee.from_str("karan-480-singer")

print(karan.no_of_leaves)
print(karan.printdetails())

 

#output:

#8

#The Name is karan. Salary is 480 and role is singer

   

#there is an alternative way of writing the code in the second @classmethod. 

#here is the code:

class Employee:
    no_of_leaves = 8

    def __init__(self, aname, asalary, arole):
        self.name = aname
        self.salary = asalary
        self.role = arole

    def printdetails(self):
        return f"The Name is {self.name}. Salary is {self.salary} and role is {self.role}"
    
    
    @classmethod
    def change_leaves(cls, newleaves):
        cls.no_of_leaves = newleaves
    
    @classmethod
    def from_str(cls, string):
        #params = string.split("-")
     
        #this is to split the string by hypen and make a list
        #print(params) if you eant to u can print and see how it makes the list
        return cls (*string.split("-"))
    #this will return the object properties from params list to the Class as commands why we used cls command and a * in the bracket.
    
harry= Employee("harry", "230", "teacher")
rohan= Employee("rohan", "333", "dancer")
karan= Employee.from_str("karan-480-singer")

print(karan.no_of_leaves)
print(karan.printdetails())

    

#output remains unchanged.

No comments:

Post a Comment