Python-- from scratch to learn object-oriented development 3
Taiyuan University of Technology Robotics Team 20 punch card day11
1, class methods and class attributes
1.1 is a special class of objects
Python in everything is an object:
- class AAA: defined category belongs to the class object
- obj1 = AAA () belonging to the instance object
- The program is running, type the same will be loaded into memory
- In Python, the class is a special object - class object
- The program runs, the class object in memory, only one , the use of a class can create a number of object instances
- In addition to the package Examples of attributes outer and methods, class objects can also have its own attributes and methods
- Class Properties
- Class Methods
- By class name . The way you can attribute access class or method calls the class
1.2 instance attributes and class attributes
- Class attribute is a class object defined attributes
- It is generally used to record relevant to this class feature
- Class attribute for not recording characteristics of the particular object
Example: In order to record the number of objects of this class
class Tool(object):
# 使用赋值语句,定义类属性,记录创建工具对象的总数
count = 0
def __init__(self, name):
self.name = name
# 针对类属性做一个计数+1
Tool.count += 1
# 创建工具对象
tool1 = Tool("斧头")
tool2 = Tool("榔头")
tool3 = Tool("铁锹")
# 知道使用 Tool 类到底创建了多少个对象?
print("现在创建了 %d 个工具" % Tool.count)
1.3 class methods and static methods
- Class property that is for the class object attribute definitions
- Use assignment statements under the class keyword to define a class attribute
- Class attribute for recording relevant to this class feature
- Class method is for the class object defined method
- In the class method inside can directly access the class properties or invoke other class methods
The syntax
@classmethod
def 类方法名(cls):
pass
- Class method requires a decorator @classmethod be identified, told the interpreter This is a class method
- Class method first parameter should be cls
- Of which class method call, cls in the way is a reference which class
- This parameter and the example method of the first parameter is a similar self
- Tip a different name can be, but the habit of using cls
- By the class name. Invoke class method , when calling the method , parameters need to pass cls
- Within a method
- By cls. Attribute access class
- You can also cls. Calling other methods of the class
Examples demand
- Define a Tools
- Each tool has its own name
- Demand in - class number of the object class of the method of packaging a show_tool_count, using the output current of this class, created
@classmethod
def show_tool_count(cls):
"""显示工具对象的总数"""
print("工具对象的总数 %d" % cls.count)
Within the class methods, may be used directly access cls class properties or calling a class method
1.4 static method
- In the development, if desired in the class encapsulates a method that:
- Not only do not need to access an instance property or call the instance method
- Also you do not need to access the class properties or by calling the class method
- This time, this method can be packaged as a static method
The syntax
@staticmethod
def 静态方法名():
pass
- Static methods needed decorator @staticmethod be identified, told the interpreter this is a static method
- By the class name. Call the static method
class Dog(object):
# 狗对象计数
dog_count = 0
@staticmethod
def run():
# 不需要访问实例属性也不需要访问类属性的方法
print("狗在跑...")
def __init__(self, name):
self.name = name
2, abnormal
- Program at run time, if the Python interpreter encounters an error, stop program execution, and prompts some wrong information, which is abnormal
- The program stops executing and an error message this action, we usually call: throw (raise) abnormal
2.1 catch the exception
- Program development, if the execution of some code can not be determined correctly , can increase the try (try) to catch the exception
- Catch exceptions simplest syntax:
try:
尝试执行的代码
except:
出现错误的处理
- try try , try to write the code below, uncertain whether the code can be executed normally
- except if not , write code below attempt fails
The type of error trapping
- During program execution, you may encounter different types of exceptions , and the need for different types of exceptions , respond differently , this time, we need to capture the type of error
- The syntax is as follows:
try:
# 尝试执行的代码
pass
except 错误类型1:
# 针对错误类型1,对应的代码处理
pass
except (错误类型2, 错误类型3):
# 针对错误类型2 和 3,对应的代码处理
pass
except Exception as result:
print("未知错误 %s" % result)
- When the Python interpreter throws an exception , the first word in the last line of the error message, type is wrong
Capture unknown error
- In the development, to anticipate all possible errors , or have some difficulty
- If you want the program to any error occurs regardless , will not because Python interpreter throws an exception has been terminated , you can add another except
The syntax is as follows:
except Exception as result:
print("未知错误 %s" % result)
Abnormal capture the full syntax
- In the actual development, in order to be able to deal with complex anomalies, abnormal complete syntax is as follows:
prompt:
- For the full syntax of scenarios, in the follow-up study, combined with actual cases will be better understood,
- Now there is a first impression to this grammatical structure
try:
# 尝试执行的代码
pass
except 错误类型1:
# 针对错误类型1,对应的代码处理
pass
except 错误类型2:
# 针对错误类型2,对应的代码处理
pass
except (错误类型3, 错误类型4):
# 针对错误类型3 和 4,对应的代码处理
pass
except Exception as result:
# 打印错误信息
print(result)
else:
# 没有异常才会执行的代码
pass
finally:
# 无论是否有异常,都会执行的代码
print("无论是否有异常,都会执行的代码")
- Code else only when there is no abnormality will be executed
- finally, whether or not there is an exception code that will be executed
- Prior to the exercise of a complete capture abnormal code is as follows
try:
num = int(input("请输入整数:"))
result = 8 / num
print(result)
except ValueError:
print("请输入正确的整数")
except ZeroDivisionError:
print("除 0 错误")
except Exception as result:
print("未知错误 %s" % result)
else:
print("正常执行")
finally:
print("执行完成,但是不保证正确")
2.2 abnormal transfer
- Abnormal transfer - when the function / method execution exception occurs , it will pass the exception to the function / method call party
- If the transfer to the main program , still no exception handler , the program will be terminated
prompt
- In development, may increase in the main function abnormalities capture
- The other function calls in the main function, as long as the abnormal, will be passed to the main function abnormalities captured in
- This eliminates the need in the code to increase the number of exception traps , to ensure clean code
demand
- The demo1 defined function () prompts the user and returns an integer
- Defined functions demo2 () call demo1 ()
- Demo2 call in the main ()
def demo1():
return int(input("请输入一个整数:"))
def demo2():
return demo1()
try:
print(demo2())
except ValueError:
print("请输入正确的整数")
except Exception as result:
print("未知错误 %s" % result)
2.3 throws raise an exception
- In development, in addition to code execution error Python interpreter throws than an exception
- You can also take the initiative to throw an exception application-specific business needs
Throw an exception
- Python is provided an exception class Exception
- In the development, if meet specific business needs, we are hoping to throw an exception, you can:
- Create an object of Exception
- Use the keyword raise thrown objects