# Python 3.0(2008/12/03) ## 新特性和改进(相比python2.x) 1. **打印函数**: - `print` 语句变为 `print()` 函数,要求使用括号。 ```python print("Hello, World!") ``` 2. **整数除法**: - `/` 运算符执行真正的浮点除法,即使两个操作数都是整数。使用 `//` 进行整数除法。 ```python print(5 / 2) # 输出: 2.5 print(5 // 2) # 输出: 2 ``` 3. **Unicode 字符串**: - 所有字符串都是 Unicode 编码,字符串字面量默认为 Unicode。 ```python s = "你好" ``` 4. **字节类型**: - 引入了新的 `bytes` 类型,用于表示字节序列。 ```python b = b"byte string" ``` 5. **移除 `dict` 的方法**: - 移除了 `dict.has_key()` 方法,使用 `in` 运算符替代。 ```python d = {'a': 1} print('a' in d) # 输出: True ``` 6. **重命名的异常类**: - 所有异常类都派生自 `BaseException`,并且统一移除了 `StandardError`。 7. **列表推导式的语法改进**: - 列表推导式不再支持隐式作用域,所有变量必须在推导式内部定义。 ```python squares = [x*x for x in range(10)] ``` 8. **迭代器和生成器**: - 内置函数和方法返回迭代器而不是列表。例如,`range()` 返回一个迭代器而不是列表。 ```python for i in range(5): print(i) ``` 9. **元类语法**: - 引入新的元类声明语法,使用 `metaclass` 关键字。 ```python class MyMeta(type): pass class MyClass(metaclass=MyMeta): pass ``` - 说明:之前语法为 ``` class MyClass: __metaclass__ = MyMeta pass ``` ## 移除语法 - Removed <> (use != instead). - Removed keyword: exec() is no longer a keyword; it remains as a function. - The from module import * syntax is only allowed at the module level, no longer inside functions. - The only acceptable syntax for relative imports is from .[module] import name. All import forms not starting with . are interpreted as absolute imports. - `xrange()` 函数被移除,使用 `range()` 替代,其行为与之前的 `xrange()` 相同。