9.6 Private Variables
class JustCounter:
__secretCount = 0 # 私有变量
publicCount = 0 # 公开变量
def count(self):
self.__secretCount +=1
self.publicCount += 1
print(self.__secretCount)
counter =JustCounter()
counter.count()
print(counter.publicCount)
类的私有方法实例如下:
class Site:
def __index__(self,name,url):
self.name = name # public
self.__url = url # private
def who(self):
print('name : ',self.name)
print('url : ',self.__url)
def __foo(self):
print('这是私有方法')
def foo(self):
print('这是公共方法')
self.__foo()
x = Site('菜鸟教程','wwww.henry.com')
x.who() #正常输出
x.foo() #正常的输出
x.__foo() #报错
运算符重载
class Vector:
def __init__(self,a,b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d %d)' % (self.a,self.b)
def __add__(self, other):
return Vector(self.a+other.a,self.b+other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print(v1+v2)
Python3 标准库预览
import os
os.getcwd()
'D:\\PycharmProjects\\untitled2'
os.chdir('/a')
Traceback (most recent call last):
File "<input>", line 1, in <module>
FileNotFoundError: [WinError 2] 系统找不到指定的文件。: '/a'
os.chdir('/untitled1')
Traceback (most recent call last):
File "<input>", line 1, in <module>
FileNotFoundError: [WinError 2] 系统找不到指定的文件。: '/untitled1'
os.system('mkdir today')
0
os.getcwd()
'D:\\PycharmProjects\\untitled2'
dir(os)
['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']
文件通配符
import glob
glob.glob('*.py')
['fibo.py']
glob.glob('*')
['fibo.py', 'today']
命令行参数
import sys
print(sys.argv)
['C:\\Program Files\\JetBrains\\PyCharm Community Edition 2017.2.3\\helpers\\pydev\\pydevconsole.py', '51333', '51334']
输出重定向和程序终止
sys.stderr.write('Warning,log file not found starting a new one\n')
46
Warning,log file not found starting a new one
字符创正则匹配
import re
re.findall(r'\bf[a-z]*','which foot or hand fell fastest')
['foot', 'fell', 'fastest']
re.sub(r'(\b[a-z]+) \1', r'\1','cat in the the hat')
'cat in the hat'
'tea for too'.replace('too','two')
'tea for two'
数学
import math
math.cos(math.pi /4)
0.7071067811865476
math.lgo(1024,2)
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: module 'math' has no attribute 'lgo'
math.log(1024,2)
10.0
import random
random.choice(['apple','peer','banana'])
'banana'
random.sample(range(100),10) # sampling without replacement
[62, 26, 18, 40, 58, 35, 53, 52, 8, 67]
random.random()
0.04803956150168376
random.randrange(6)
4
访问互联网
import smtplib
server = smtplib.SMTP('localhost')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python\Python36-32\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python\Python36-32\lib\smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python\Python36-32\lib\smtplib.py", line 307, in _get_socket
self.source_address)
File "C:\Python\Python36-32\lib\socket.py", line 724, in create_connection
raise err
File "C:\Python\Python36-32\lib\socket.py", line 713, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。
数据压缩
import zlib
s = b'witch which has which witches wrist watch'
len(s)
41
t = zlib.compress(t)
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 't' is not defined
t = zlib.compress(s)
len(t)
37
zlib.decompress(t)
b'witch which has which witches wrist watch'
zlib.crc32(s)
226805979
性能度量
from timeit import Timer
Timer('t=a; a=b; b=t', 'a=1;b=2').timeit()
0.05319468214902286
Timer('a,b =b,a','a=1;b=2').timeit()
0.061133142520006345
测试模块
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40.0
"""
return sum(values) / len(values)
import doctest
doctest.testmod()
TestResults(failed=0, attempted=0)
import unittest
class TestStatisticlaFunctions(unittest.TestCase):
def test_average(self):
self.asserEqual(average([20,30,70]),40.0)
self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
self.assertRaises(ZeroDivisionError,average,[])
self.assertRaises(TypeError,average,20,30,70)
unittest.main()
EE
======================================================================
ERROR: 51333 (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute '51333'
======================================================================
ERROR: 51334 (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute '51334'
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (errors=2)
python 计算每个月的天数
import calendar
monthRange = calendar.monthrange(2017,11)
print(monthRange)
(2, 30)
print(calendar.mdays[11])
30
python 九九乘法表
for i in range(1,10):
for j in range(1,i+1):
print('{}x{}={}\t'.format(i,j,i*j),end='')
print()
1x1=1
2x1=2 2x2=4
3x1=3 3x2=6 3x3=9
4x1=4 4x2=8 4x3=12 4x4=16
5x1=5 5x2=10 5x3=15 5x4=20 5x5=25
6x1=6 6x2=12 6x3=18 6x4=24 6x5=30 6x6=36
7x1=7 7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49
8x1=8 8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64
9x1=9 9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81
网友评论