python3基础练习

最近业务上在写一个基于串口的python-sdk

写下来真觉得python是个好东西,简单、强大、生态好!

当然了,也有许多要注意的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

class Hello():
name = 'dottie'
def __init__(self):
self._age = 11

@property
def age(self):
print('get', self._age)
return self._age

# 可以进行参数校验
# 该方法内不能调用self.age = xxx 会导致递归
@age.setter
def age(self, age):
print('set', age)
if age < 10:
raise ValueError('值不能小于10')
self._age = age + 1

def set_name(self, name):
self.name = name

# 类方法比静态方法就是多了一个默认参数,
# 类似 实例方法第一个参数是self
@classmethod
def hello(cls):
'''cls为该类'''
print('classmethod', cls.name)

@staticmethod
def world():
print('staticmethod', Hello.name)

# 私有实例方法
def _hey(self):
print('>>> hello {}'.format('guys'))
print(f'hello{"guy"}')
return 'hey guys!'




Hello.name = 'daejong'
hello = Hello()

# 类属性可以用类名和self访问。
# 但是只能通过类名调用类属性来修改类属性值
# 通过self调用类属性只能访问类属性(只读)
print(hello.name) # daejong 这里访问的是类属性
print(Hello.name) # daejong 这里访问的是类属性

hello.set_name('china')
print(hello.name) # china 这里访问的实例属性name
print(Hello.name) # daejong 这里访问的是类属性

print(hello.age) # 11


hello.age = 22
print(hello.age) # 22

hello.hello() # classmethod daejong
Hello.hello() # classmethod daejong

hello.world() # staticmethod daejong
Hello.world() # staticmethod daejong

class Child(Hello):
pass


print(Child.name)

Child.hello() # classmethod daejong
Child.world() # staticmethod daejong

child = Child()
child.hello() # classmethod daejong
child.world() # staticmethod daejong
print(child.name) # daejong
print(child.age) # 11