python 教程笔记day7

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  

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,820评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,648评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,324评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,714评论 1 297
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,724评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,328评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,897评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,804评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,345评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,431评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,561评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,238评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,928评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,417评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,528评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,983评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,573评论 2 359

推荐阅读更多精彩内容

  • 一、异同对比选择1、Python和ruby的相同点: * 都强调语法简单,都具有更一般的表达方式。python是缩...
    沃伦盖茨阅读 4,148评论 2 24
  • Python是一种对代码风格很重视的语言,从缩进就能看出这一点,Python强调易于理解。最近在负责代码重构的工作...
    知曰阅读 10,919评论 1 85
  • 多久没有画一幅作品,我自己都记不起来了,记得上次是画了池塘边的荷花,那应该是一个星期。选择很重要,你选择了做些什么...
    清文雅书阅读 189评论 2 1
  • 计划制定人 安安和妈妈 计划执行人 全家人 第一天的计划,从8点后开始的,前面属于...
    Jessica_Love阅读 378评论 0 0
  • ​ 房子这件事,自古至今都是大事,从造字法“安”和“家”都有宝盖头儿就能看出来房屋的重要性,宝盖头指“指状如屋顶的...
    一只努力的蟹阅读 8,425评论 41 38