python 对象

1.创建python类

python类要注意驼峰式命名。

添加属性

可以通过点记法对空类进行后创建属性😅,这个真的是太神奇了。

1
2
3
4
5
class Point:
Pass
p = Point()
p.x = 1
p.y = 2

2.初始化函数和构造函数

1
2
3
4
5
6
7
class Point:
def __init__(self, x = 0, y = 0):#在这里可以设置一个默认值
self.move(x, y)
def move(self, x, y):
self.x = x
self.y = y

3.解释自己

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Point:
'This is a new class by yelin'
def __init__(self, x = 0, y = 0):
"""
This is a function, it move center of the
class to a new place
"""
self.move(0, 0)
def move(self, x, y):
"I want to add some comment."
self.x = x
self.y = y

4.模块

千万不要使用如下写法, 因为它为导致命名空间的混乱,不利于查看源文件,代码维护变成噩梦,import * 会破坏代码补全:

1
from database import *

4.1 组织模块

一个package就是放到一个文件夹里的模块集合,

1
2
3
4
5
6
7
8
9
10
11
12
```python
parent_directory/
main.py
ecommerce/
__init__.py
database.py
products.py
payments/
__init__.py
paypal.py
authorizenet.py

5.数据访问

双下划线开头的变量并不是不可被访问的, 被”命名改编“后,只需要调用改编之后的变量名就可以调用了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class SecretString:
'''A not-at-all secure way to store a secret string.'''
def __init__(self, plain_string, pass_phrase):
self.__plain_string = plain_string
self.__pass_phrase = pass_phrase
def decrypt(self, pass_phrase):
'''Only show the string if the pass_phrase is correct'''
if pass_phrase == self.__pass_phrase:
return self.__plain_string
else:
return
secret_string = SecretString("ACME: Top Secret", "antwerp")
print(secret_string._SecretString__plain_string)

6.重载

1
2
3
4
class Friend(Concat):
def __init__(self, name, email, phone):
super().__init__(name, email)
self.phone = phone