class Dog: # Class Object Attribute species = 'mammal' def __init__(self,breed,name): self.breed = breed self.name = name
Lets break down what we have above.The special method
__init__()
is called automatically right after the object has been created, similer to construct() in php
self argument is necessary in python, php has default so no need to pass in php
sam = Dog('Lab','Sam') //here creating the instance of the class, no need to pass new keyword in python
Inheritance:
class Animal: def __init__(self): print("Animal created") def whoAmI(self): print("Animal") class Dog(Animal): // Inherating the Animal Class def __init__(self): Animal.__init__(self) print("Dog created")
Error Handling & Exception :
try: f = open('testfile','r') f.write('Test write this') except IOError: # This will only check for an IOError exception and then execute this print statement print("Error: Could not find file or read data") else: print("Content written successfully") f.close()
Here first try to run the code in try block if any error related to IOerror then it will log otherwise else will run
so either except or else will run ,
def askint(): try: val = int(input("Please enter an integer: ")) except: print("Looks like you did not enter an integer!") finally: print("Finally, I executed!") print(val) Here Finally Block will execute everytime either it pass or fail.
Comments
Post a Comment