零基础学习Python,有疑惑,请大师们解疑:
1、pygame.Rect(left,top,width,height)和pygame.rect.Rect(left,top,width,height),Rect(left,top,width,height)三种写法分别是怎么解释的?
2、有点区分不清大写Rect和小写rect(Python中区分大小写?)
3、Rect/rect 是对象?还是方法,还是类?(完全弄混了。。。)
Rect是类,跟着括号,那个是构造函数,rect是变量。
(1)实际上 pygame.Rect 与 Rect 实际上是同一句话 => (pygame.)Rect。
如果只 import pygame 的话,第一句不会报错,而第二句会报错。
>>> import pygame
>>> Rect
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
Rect
NameError: name 'Rect' is not defined
>>> pygame.Rect
<class 'pygame.Rect'>
但是,如果像下面你这么做的话,两者都不会报错
这要跟包管理和命名空间有关系,可以理解为把 Pygame 库中的 Rect 直接拉出来,作为全局变量
>>> import pygame
>>> from pygame import Rect
>>> Rect
<class 'pygame.Rect'>
>>> pygame.Rect
<class 'pygame.Rect'>
而且我们可以发现,两者返回的一致。
(2)pygame.Rect 与 pygame.rect.Rect 的关系问题
我测试的结果,好像是一个东西。
pygame 官方文档也没单独给出 pygame.rect 的说明
>>> help(pygame.Rect)
Help on class Rect in module pygame:
class Rect(builtins.object)
| Rect(left, top, width, height) -> Rect
| Rect((left, top), (width, height)) -> Rect
| Rect(object) -> Rect
| pygame object for storing rectangular coordinates
...
>>> help(pygame.rect.Rect)
Help on class Rect in module pygame:
class Rect(builtins.object)
| Rect(left, top, width, height) -> Rect
| Rect((left, top), (width, height)) -> Rect
| Rect(object) -> Rect
| pygame object for storing rectangular coordinates
...
>>> pygame.rect.Rect(0, 0, 0, 0)
<rect(0, 0, 0, 0)>
>>> pygame.rect.Rect(0, 0, 0, 0) == pygame.Rect(0, 0, 0, 0)
True
>>> pygame.rect.Rect(0, 0, 0, 0) is pygame.Rect(0, 0, 0, 0)
False
>>> pygame.rect == pygame.Rect
False
>>> pygame.rect.Rect(0, 1, 2, 3).top
1
>>> pygame.Rect(0, 1, 2, 3).top
1
>>> pygame.rect.Rect(0, 1, 2, 3).size
(2, 3)
>>> pygame.Rect(0, 1, 2, 3).size
(2, 3)
>>> pygame.Rect(0, 2, 3, 4).move(1,1)
<rect(1, 3, 3, 4)>
>>> pygame.rect.Rect(0, 2, 3, 4).move(1,1)
<rect(1, 3, 3, 4)>
两者功能也基本一致。
相关链接:Pygame中rect 初探
个人见解就是二选一,如果真的有区别,我也不知道,看上好像都可以。
(3)对于类和方法的区分
在交互模式下,尝试用没有括号的语句进行
>>> pygame.Rect
<class 'pygame.Rect'>
>>>pygame.rect.Rect
<class 'pygame.Rect'>
>>> pygame.rect.Rect(0, 2, 1, 2).move
<built-in method move of pygame.Rect object at 0x00000193048D3AF8>
>>> pygame.Rect(0, 2, 1, 2).move
<built-in method move of pygame.Rect object at 0x0000019304FE2F08>
可以理解为必须出现实例之后,对这个实例后续的.xxxx
就是方法