Python Basic Introduction to Magic Methods and Exception Handling

  • 2021-12-13 08:46:05
  • OfStack

Directory 1. Magic Method 1. Attribute Access 2. Descriptor 3. Custom Sequence 5. Generator 2. Exception Handling 1. Exception Types 2. try-except Statements 3. try-finally Statements 4. raise Statements 5. Rich Summary of else Statements

1. Magic methods

1. Attribute access

Usually, you can access the properties of objects in the form of point (.) operators.


class C:
	def __init__(self):
		self.x='X-man'
c=C()
c.x
'X-man'
getattr(c , 'x' , ' Wood has this attribute ')
'X-man'
getattr(c , 'y' , ' Wood has this attribute ')
' Wood has this attribute '

Magic method:

(1) Defines the behavior when a user attempts to get a non-existent attribute.


__getattr__(self,name)	

(2) Defines the behavior when the properties of the class are accessed.


__getattribute__(self,name)

(3) Defines the behavior when 1 attribute is set.


__setattr__(self,name,value)

(4) Defines the behavior when an attribute is deleted.


__delattr__(self,name)

2. Descriptors

(1) Used to access a property, which returns the value of the property.


__get__(self,instance,owner)

(2) Will be called in a property assignment operation and will return nothing.


__set__(self,instance,value)

(3) Control the deletion operation without returning anything.


__delete__(self,instance)

class MyDescriptor:
    def __get__(self,instance,owner):
        print("getting...",self,instance,owner)
    def __set__(self,instance,value):
        print("setting...",self,instance,value)
    def __delete__(self,instance):
        print("deleting...",self,instance)
class Test:
    x =MyDescriptor()

3. Customize the sequence

Magic method:


__len__(self)
__getitem__(self,key)
__setitem__(self,key,value)
__delitem__(self,key)
__iter__(self)
__reversed__(self)
__contains__(self,item)

4. Iterators


__getattr__(self,name)	
0

A string is a container and an iterative object. The function of for statement is to trigger its iterative function, and take out one data from the container in turn at a time, which is the iterative operation.

Python provides two BIF: iter () and next ().

Calling iter () on an iterable object gets its iterator, and calling next () iterator returns the next value.


__getattr__(self,name)	
1

5. Generator

For calling a normal Python function, 1 usually starts with line 1 of the function and ends with an return statement, an exception, or all statements.

2. Exception handling

1. Type of exception

(1) AssertionError: The assertion statement (assert) failed.


__getattr__(self,name)	
2

(2) AttributeError: Attempt to access an unknown object property.


my_list=[]
my_list.fishc
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    my_list.fishc
AttributeError: 'list' object has no attribute 'fishc'

(3) IndexError: Index is out of range of sequence.


__getattr__(self,name)	
4

(4) KeyError: Find a keyword that does not exist in the dictionary.


__getattr__(self,name)	
5

(5) NameError: Attempt to access a variable that does not exist.


__getattr__(self,name)	
6

(6) OSError: An exception generated by the operating system.

(7) SyntaxError: Syntax error in Python.


__getattr__(self,name)	
7

(8) TypeError: Invalid operation between different types.


1+'1'
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    1+'1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

(9) ZeroDivisionError: The divisor is zero.


__getattr__(self,name)	
9

2. try-except statement


try:
    int('abc')
    sum =1+'1'
    f =open(' I am 1 Documents that do not exist .txt')
    print(f.read())
    f.close()
except (ValueError,TypeError,OSError) as reason:
    print(' Error \n The cause of the error is :'+str(reason)')

3. try-finally statement


try:
    f =open(' I am 1 Documents that do not exist .txt')
print(f.read())
	sum=1+'1'
except:
	print(' There's been a mistake ')
finally:
	f.close()

4. raise statement


raise ZeroDivisionError5/0
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    5/0
ZeroDivisionError: division by zero

5. Rich else statements


__getattribute__(self,name)
3

Summarize


Related articles: