Wprowadzenie
do języka Python
- Wykład 5

“Obiektowość”

Programowanie obiektowe w Pythonie

Lego jako model programowanie obiektowego

class Employee:
    """Common base class for all employees"""
    empCount = 0

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1

    def displayCount(self):
        print("Total Employee %d" % Employee.empCount)

    def displayEmployee(self):
        print("Name : ", self.name, ", Salary: ",
              self.salary)


emp1 = Employee("John", 2000)
emp2 = Employee("Anna", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
Name :  John , Salary:  2000
Name :  Anna , Salary:  5000

Obsługa błędów

Dokumentacja https://docs.python.org/3/tutorial/errors.html

10 * (1/0)
4 + spam*3
'2' + 2
try:
    x = int(input("Please enter a number: "))
    print("number", x)
except ValueError:
    print("Oops!  That was no valid number.  Try again...")
while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops!  That was no valid number.  Try again...")
print("number", x)
try:
    raise Exception('spam', 'eggs')
except Exception as inst:
    print(type(inst))    # the exception instance
    print(inst.args)     # arguments stored in .args
    print(inst)          # __str__ allows args to be printed directly,
                         # but may be overridden in exception subclasses
    x, y = inst.args     # unpack args
    print('x =', x)
    print('y =', y)
def this_fails():
    x = 1/0
try:
    this_fails()
except ZeroDivisionError as err:
    print('Handling run-time error:', err)

try:
    raise KeyboardInterrupt
finally:
    print('Goodbye, world!')
    
def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("division by zero!")
    else:
        print("result is", result)
    finally:
        print("executing finally clause")
        
        
divide(2, 1)
divide(2, 0)
divide("2", "1")

Bibliografia