跳至主要内容

python 之 深入理解

# 一旦遇到第一个return,函数执行就会停止
def three():
    print(1)
    return 2
    print(3)
    return 22 
 
three()
print(4)
----------------------
for i in range(10):
    line = ""
    for j in range(10):
        if i == j:
            break
        line += "{} ".format(j)
    print(line)
-----------------------
魔法函数
__init__ :初始化类的新实例 Initialize a new instance of the class
__new__ :创建该类的新实例 Create a new instance of the class
__repr__ :定义实例表示进行调试 Define an instance representation for debugging
__str__ :定义实例的用户友好表示 Define user-friendly representation of an instance


class Song:
    def __init__(self, artist, name, year):
        self.artist = artist
        self.name = name
        self.year = year
 
    def __repr__(self):
        rep = "Artist: {}. Name: {}. Year: {}".format(self.artist, self.name,
                                                      self.year)
        return rep
 
    def __str__(self):
        return "{} — {} ({})".format(self.artist, self.name, self.year)
    
dsmn = Song("Queen", "Don't stop me now", 1979)
print(dsmn)


----------
# 如果不使用global关键字,则无法在函数内部更改全局变量的值

x = "global"
def outer():
    x = "outer local"
    def inner():
        x = "inner local"
        def func():
            x = "func local"
            print(x)
        func()
    inner()
 

# nonlocal 关键字可让我们将变量分配给外部(而非全局)范围

def func():
    x = 1
    def inner():
        x = 2
        print("inner:", x)
    inner()
    print("outer:", x)
 
def nonlocal_func():
    x = 1
    def inner():
        nonlocal x
        x = 2
        print("inner:", x)
    inner()
    print("outer:", x)
 
func()  # inner: 2
        # outer: 1
 
nonlocal_func()  # inner: 2
                 # outer: 2

outer()

---------------------------------
def func(positional_args, args_with_default, *args, **kwargs):
pass


print(*"fun") # f u n
print(*[5, 10, 15]) # 5 10 15

def add(*args):
total = 0
for n in args:
total += n
return total


small_numbers = [1, 2, 3]
large_numbers = [9999999, 1111111]

print(add(*small_numbers)) # 6
print(add(*large_numbers)) # 11111110


def say_bye(**names):
for name in names:
print("Au revoir,", name)

for key, value in names.items():
print(f"{key}:{value}")


humans = {"Laura": {"age": 34, "fave_color": "purple"},
"Robin": {"age": 28, "fave_color": "turquoise"}}
say_bye(**humans)

# Au revoir, Laura
# Au revoir, Robin
# Laura:{'age': 34, 'fave_color': 'purple'}
# Robin:{'age': 28, 'fave_color': 'turquoise'}

def concat(*args):
return "".join(args)
print(concat("python")) # python
print(concat("cat", "dog")) # catdog

def create_function(n):
return lambda x: n * x

# Creating a function that doubles its argument
doubler = create_function(2)

# This function will triple its argument
tripler = create_function(3)

doubler(2)
# Outputs 4

tripler(2)
# Outputs 6

-------------------------------
def func(x):
if x % 2 == 0:
return 'even'
else:
return 'odd'

func = (lambda x: 'even' if x % 2 == 0 else 'odd')
---------------------------

评论

此博客中的热门博文

自动发送消息

  # https://pyperclip.readthedocs.io/en/latest/ import pyperclip while True :     # pyperclip.copy('Hello, world!')     # pyperclip.paste()     # pyperclip.waitForPaste()     print ( pyperclip. waitForNewPaste ( ) )     # 获取要输入新的坐标,也可以通过autohotkey import time import pyautogui  as pag import os   try :     while True :         print ( "Press Ctrl-C to end" )         x , y = pag. position ( )   # 返回鼠标的坐标         posStr = "Position:" + str ( x ) . rjust ( 4 ) + ',' + str ( y ) . rjust ( 4 )         print ( posStr )   # 打印坐标         time . sleep ( 0.2 )         os . system ( 'cls' )   # 清楚屏幕 except KeyboardInterrupt :     print ( 'end....' )     # 打印消息 import pyautogui import time import pyperclip   content = """   呼叫龙叔! 第二遍! 第三遍! 第四遍...

学习地址

清华大学计算机系课程攻略 https://github.com/PKUanonym/REKCARC-TSC-UHT 浙江大学课程攻略共享计划 https://github.com/QSCTech/zju-icicles https://home.unicode.org/ 世界上的每个人都应该能够在手机和电脑上使用自己的语言。 http://codecanyon.net   初次看到这个网站,小伙伴们表示都惊呆了。原来代码也可以放在网上卖的?!! 很多coder上传了各种代码,每个代码都明码标价。看了下销售排行,有的19刀的卖了3万多份,额di神啊。可以看到代码的演示效果,真的很漂亮。代码以php、wordpress主题、Javascript、css为主,偏前台。 https://www.lintcode.com/ 算法学习网站,上去每天刷两道算法题,走遍天下都不怕。 https://www.codecademy.com/ 包含在线编程练习和课程视频 https://www.reddit.com/ 包含有趣的编程挑战题,即使不会写,也可以查看他人的解决方法。 https://ideone.com/ 在线编译器,可运行,可查看代码示例。 http://it-ebooks.info/ 大型电子图书馆,可即时免费下载书籍。 刷题 https://github.com/jackfrued/Python-100-Days https://github.com/kenwoodjw/python_interview_question 面试问题 https://github.com/kenwoodjw/python_interview_question https://www.journaldev.com/15490/python-interview-questions#python-interpreter HTTP 身份验证 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Authentication RESTful 架构详解 https://www.runoob.com/w3cnote/restful-architecture.html https://www.rosettacode.org/wiki/Rosetta_C...

mysql 入门

资料 https://dinfratechsource.com/2018/11/10/how-to-install-latest-mysql-5-7-21-on-rhel-centos-7/ https://dev.mysql.com/doc/refman/5.7/en/linux-installation-yum-repo.html https://www.runoob.com/mysql/mysql-create-database.html https://www.liquidweb.com/kb/install-java-8-on-centos-7/ 工具 https://www.heidisql.com/ HeidiSQL是免费软件,其目标是易于学习。 “ Heidi”使您可以从运行数据库系统MariaDB,MySQL,Microsoft SQL或PostgreSQL的计算机上查看和编辑数据和结构 MySQL 连接时尽量使用 127.0.0.1 而不是 localhost localhost 使用的 Linux socket,127.0.0.1 使用的是 tcp/ip 为什么我使用 localhost 一直没出问题 因为你的本机中只有一个 mysql 进程, 如果你有一个 node1 运行在 3306, 有一个 node2 运行在 3307 mysql -u root -h localhost -P 3306 mysql -u root -h localhost -P 3307 都会连接到同一个 mysql 进程, 因为 localhost 使用 Linux socket, 所以 -P 字段直接被忽略了, 等价于 mysql -u root -h localhost mysql -u root -h localhost 而 -h 默认是 localhost, 又等价于 mysql -u root mysql -u root 为了避免这种情况(比如你在本地开发只有一个 mysql 进程,线上或者 qa 环境有多个 mysql 进程)最好的方式就是使用 IP mysql -u root -h 127 .0 .0 .1 -P 3307 strac...