程序员之所以犯错误,不是因为他们不懂,而是因为他们自以为什么都懂。
class MyClass:
def __init__(self, name):
self.name = name
def __str__(self):
print('print will call __str__ first.')
return 'Hello ' + self.name + '!'
print(MyClass('Tom'))
结果 :
print will call __str__ first.
Hello Tom!
def init(self, name):
self.name = name
def say_hello(self):
print('Hello, %s!' % self.name)
# Hello = type('Hello', (object, ), dict(__init__ = init, hello = say_hello))
Hello = type('Hello', (object, ), {'__init__':init, 'hello':say_hello})
'''
class Hello:
def __init__(...)
def hello(...)
'''
h = Hello('Tom')
h.hello()
结果 :
Hello, Tom!
class MyDict(dict):
pass
class TestMyDict(unittest.TestCase):
def setUp(self):
print('测试前准备')
def tearDown(self):
print('测试后清理\n')
def test_init(self):
md = MyDict(one = 1, two = 2)
self.assertEqual(md['one'], 1)
self.assertEqual(md['two'], 2)
# self.assertEqual(md['two'], 3)
print("这里执行几遍")
def test_nothing(self):
print("凡是test打头的都执行,其它不执行")
pass
def something(self):
print("每次测试前后都执行准备和清理")
if __name__ == '__main__':
unittest.main()
结果 :
测试前准备
这里执行几遍
测试后清理测试前准备
凡是test打头的都执行,其它不执行
测试后清理python的单元测试
li = [1, 2, 3, '456', [1, 2, 3], {1: 'one', 2: 'two'}]
print(type(list))
print(type(li))
# 元素访问
print(li[0])
print(li[-1]) # li[len(li) - 1]
print(li[-2]) # li[len(li) - 2]
结果 :
<class 'type'>
<class 'list'>
1
{1: 'one', 2: 'two'}
[1, 2, 3]
# 查找元素位置
print(li.index('456'))
print(li.index([1, 2, 3]))
# print(li.index(-1))
结果 :
3
4
# 添加元素
l_a = [1, 2, 3]
l_a.append(4)
l_a.append(5)
l_b = [6, 7, 8]
l_a.extend(l_b) # 试下用append是什么结果
print(l_a)
l_a = []
if not l_a:
print('Empty') # not XX和is None不是一回事
if len(l_a) == 0:
print('Empty')
结果:
[1, 2, 3, 4, 5, 6, 7, 8]
Empty
Empty
for i in li:
print(i)
for i in range(len(li)):
print(li[i])
t = (1, 2, 3, '456')
print(type(t))
# t[0] = 'a'
# t.append('x')
结果 :
1
2
3
456
[1, 2, 3]
{1: 'one', 2: 'two'}
1
2
3
456
[1, 2, 3]
{1: 'one', 2: 'two'}
<class 'tuple'>
del(li[-1]) # del(list[index])
del(li[1])
del(li[-2])
print(li)
结果:
[1, 3, [1, 2, 3]]