Write a program in python: Define a class with methods

 


Write a code in python and follow these steps:

  • Define a class name Person 
  • Define __init__ method and pass title,name,surname
  • Define print class to print details
  • Use rasie function to include error statment 
Solution:

_Author__='Simulation-hub'
class Person:
Title=('Mr','Mrs','Dr','Ms')
def __init__(self,t,name,surname):
if t not in self.Title:
raise ValueError("%s is not a valid title "%t)
self.t=t
self.name=name
self.surname=surname
def print(self):
print("%s. %s %s is mater of sciecne "% (self.t, self.name, self.surname))
person=Person( 'Mr','shivam','choubey') #object of class Person
person.print()
shiv=Person('Dr','shivam','choubey')# Object of class Perosn
shiv.print()
print(Person.Title)
print(person.Title)# object is also free to access variable
view raw Perosn.py hosted with ❤ by GitHub
Mr. shivam choubey is mater of sciecne 
Dr. shivam choubey is mater of sciecne 
('Mr', 'Mrs', 'Dr', 'Ms')
('Mr', 'Mrs', 'Dr', 'Ms')

0 Comments