Python 3.3 Tutorial Notes - 7:Class

本文详细解析了Python中命名空间的概念、生命周期、作用范围及模块间的关系,通过实例展示了局部、全局和非局部变量的作用过程,并讨论了类定义、属性赋值与删除、作用域层级以及类与实例对象之间的关系。
1. Allow multiple base classes
2. namespace: Most namespaces are currently implemented as Python dictionaries
3. attribute: 
     3.1 for any name following a dot — for example, in the expression z.real
     3.2 Writable attributes may also be deleted with the del statement.
4. namespace life time
     4.1 The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted.
     4.2 The global namespace for a module is created when the module definition is read in
     4.3 normally, module namespaces also last until the interpreter quits.
     4.4 The local namespace for a function is created when the function is called, and deleted when the function returns or raises an exception that is not handled within the function.
     4.5 Recursive invocations each have their own local namespace.
5. Existing modules
     5.1 The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively, are considered part of a module called __main__
     5.2 The built-in names actually also live in a module; this is called builtins
6. Scope:
     6.1 A scope is a textual region of a Python program where a namespace is directly accessible.
     6.2 “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.
     6.3 scopes are determined statically, they are used dynamically.
          6.3.1 the innermost scope, which is searched first, contains the local names
          6.3.2 the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
          6.3.3 the next-to-last scope contains the current module’s global names
          6.3.4 the outermost scope (searched last) is the namespace containing built-in names
     6.4 Sample
def scope_test():
  def do_local():
    spam = "local spam"
    print("do_local: " + spam)
  def do_nonlocal():
    nonlocal spam
    spam = "nonlocal spam"
    print("do_nonlocal: " + spam)
  def do_global():
    global spam
    spam = "global spam"
    print("do_global: " + spam)

  spam = "test spam"
  print("original: " + spam)
  print()
  do_local()
  print("After local assignment:", spam)
  print()
  do_nonlocal()
  print("After nonlocal assignment:", spam)
  print()
  do_global()
  print("After global assignment:", spam)
  print()

#spam = ''
scope_test()
print("In global scope:", spam)
----------------------------------------------------
original: test spam

do_local: local spam
After local assignment: test spam

do_nonlocal: nonlocal spam
After nonlocal assignment: nonlocal spam

do_global: global spam
After global assignment: nonlocal spam

In global scope: global spam
     6.5 if no global statement is in effect – assignments to names always go into the innermost scope.
     6.6 all operations that introduce new names use the local scope: in particular, import statements and function definitions bind the module or function name in the local scope.
7. Class could be defined in an if-branch or inside a function
8. When a class definition is entered, a new namespace is created, and used as the local scope
9. Class constructor: __init__(). If the class has this, it will be invoked when create new instance. It can has parameters, but first one is "self"
10. If an attribute is changed by <class_name>.<attribute_name>, it is changed for all instances which have not assign value to this attribute. If the instance object already set some value to this attribute, the change in class object will not impact it.
11. The instance object could contain some attributes which are not in the class object. Same thing can happen with "del".
12. The function in an instance object is called "method object", the function in a class object is called "function object"
13. A method object could be saved to another variable and use it later, before the instance object out of life scope
14. Python class is not designed to hide data. Taken care by programmer.
15. Need to manually maintain the name. Pay attention to override locally.
16. It is not necessary that the function definition is textually enclosed in the class definition: assigning a function object to a local variable in the class is also ok.
17. Each value is an object, and therefore has a class (also called its type). It is stored as object.__class__.
18. class DerivedClassName(modname.BaseClassName):
19. All methods in Python are   virtual
20. a simple way to call the base class method directly: just call  BaseClassName.methodname(self, arguments).
21. isinstance(<object>, <class_name>), issubclass(<class_name>, <base_class_name>)
22. For multiple inheritance, search for attribute is deep-first, left-to-right. For deeper understanding, there is a way to avoid a base class been searched more than once. 
23. There is NO private instance variable. A name with underscore as prefix should be non-public. This is an implementation detail and could be changed in the future.
24. name mangling: Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.
25. Notice that code passed to exec() or eval() does not consider the classname of the invoking class to be the current class
26. Instance method objects have attributes, too: m.__self__ is the instance object with the method m(), and m.__func__ is the function object corresponding to the method.
27. if there are more than 1 "except" clause after "try", the first matched will be triggered and ignore other options.
28. iter(): create an iterator object
29. add iterator behavior to a class: define __iter__() in the class return an object which has __next__()
30. Generator: 
     30.1 Use "yield" statement to create an iterator: use "yield" other than "return" when you want to return something. then every time "__next__" is called, the value will return and resume the iteration in the method using "yield"
     30.2 the local variables and execution state are automatically saved between calls.
     30.3 when generators terminate, they automatically raise StopIteration.

Sample Code:
1. Iterator.py
2. Scope.py
3. Class1.py
4. Class2.py
内容概要:本文围绕六自由度机械臂的人工神经网络(ANN)设计展开,重点研究了正向与逆向运动学求解、正向动力学控制以及基于拉格朗日-欧拉法推导逆向动力学方程,并通过Matlab代码实现相关算法。文章结合理论推导与仿真实践,利用人工神经网络对复杂的非线性关系进行建模与逼近,提升机械臂运动控制的精度与效率。同时涵盖了路径规划中的RRT算法与B样条优化方法,形成从运动学到动力学再到轨迹优化的完整技术链条。; 适合人群:具备一定机器人学、自动控制理论基础,熟悉Matlab编程,从事智能控制、机器人控制、运动学六自由度机械臂ANN人工神经网络设计:正向逆向运动学求解、正向动力学控制、拉格朗日-欧拉法推导逆向动力学方程(Matlab代码实现)建模等相关方向的研究生、科研人员及工程技术人员。; 使用场景及目标:①掌握机械臂正/逆运动学的数学建模与ANN求解方法;②理解拉格朗日-欧拉法在动力学建模中的应用;③实现基于神经网络的动力学补偿与高精度轨迹跟踪控制;④结合RRT与B样条完成平滑路径规划与优化。; 阅读建议:建议读者结合Matlab代码动手实践,先从运动学建模入手,逐步深入动力学分析与神经网络训练,注重理论推导与仿真实验的结合,以充分理解机械臂控制系统的设计流程与优化策略。
<think>嗯,用户想查看mysqlclient包的详细信息,特别是关于Python方面的。首先,我需要回忆一下mysqlclient的基本情况。mysqlclient是Python连接MySQL的一个驱动程序,支持Python3,这点用户提供的引用里也提到了[^1][^2]。接下来,我应该整理出它的主要特点,比如兼容性、依赖库、功能支持等。 然后,安装方法部分,用户可能想知道不同系统下的安装命令。记得在Linux上需要安装python3-dev和默认的libmysqlclient-dev,引用中的例子提到了CentOS可能遇到的问题[^3]。Windows用户可能需要预编译的二进制包,这里可以提到pip安装的命令。 接下来是基本用法,需要给出一个简单的代码示例,展示如何连接数据库、执行查询,这部分要确保代码正确,比如使用cursor.execute和fetchall方法。用户可能还关心错误处理和性能优化,所以高级特性部分要提到上下文管理器和事务支持。 常见问题方面,用户可能会遇到依赖缺失或者版本冲突,比如Python.h找不到,这时候需要指出安装python3-dev。另外,引用中提到了MySQL-python只支持Python2,而mysqlclient是分支支持Python3,这点要强调兼容性问题[^2]。 最后,相关资源部分需要列出项目地址和文档链接,引用里的GitCode和PyPI页面[^2][^4]。这样用户可以直接访问官方资源获取更多信息。整个回答要保持结构清晰,分点说明,确保用户能一步步了解mysqlclient的各个方面。</think>### mysqlclient 包详情(Python) #### 1. **概述** - **mysqlclient** 是 Python 连接 MySQL 数据库的常用驱动库,支持 Python 3.x,是 MySQL-python(仅支持 Python 2)的替代分支。 - 提供高效的原生 SQL 操作接口,底层基于 MySQL C API 实现。 #### 2. **主要特性** - 兼容 Python 3.x 和 Python 2.7+。 - 依赖 MySQL 客户端库(如 `libmysqlclient-dev` 或 `mysql-connector-c`)。 - 支持事务、连接池、参数化查询等数据库操作。 - 提供与 MySQL-python 高度兼容的 API。 #### 3. **安装方法** - **Linux/Unix**: ```bash # 安装依赖 sudo apt-get install python3-dev default-libmysqlclient-dev # Debian/Ubuntu sudo yum install python3-devel mysql-devel # CentOS/RHEL # 安装包 pip install mysqlclient ``` - **Windows**:需预安装 MySQL 客户端库或使用预编译的二进制包: ```bash pip install mysqlclient ``` #### 4. **基本用法示例** ```python import MySQLdb # 连接数据库 conn = MySQLdb.connect( host="localhost", user="root", password="password", database="test_db" ) # 执行查询 cursor = conn.cursor() cursor.execute("SELECT * FROM users") results = cursor.fetchall() for row in results: print(row) # 关闭连接 cursor.close() conn.close() ``` #### 5. **高级特性** - **事务管理**: ```python try: conn.begin() cursor.execute("INSERT INTO users (name) VALUES (&#39;Alice&#39;)") conn.commit() except Exception as e: conn.rollback() ``` - **上下文管理器**(Python 3+): ```python with conn.cursor() as cursor: cursor.execute("SELECT @@version") print(cursor.fetchone()) ``` #### 6. **常见问题** - **依赖缺失错误**(如 `Python.h not found`):需安装 `python3-dev` 或 `mysql-devel`。 - **兼容性问题**:若项目原使用 MySQL-python,可无缝替换为 mysqlclient。 - **性能优化**:通过 `cursorclass=MySQLdb.cursors.DictCursor` 返回字典格式结果。 #### 7. **相关资源** - 项目地址:[GitCode 仓库](https://gitcode.com/gh_mirrors/mysqlclient) - 文档:[PyPI 页面](https://pypi.org/project/mysqlclient/)[^4] ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值