万字干货,Python语法大合集,一篇文章带你入门( 十 )

执行这个类:
if __name__ == '__main__':sup = Batman()# Get the Method Resolution search Order used by both getattr() and super().# This attribute is dynamic and can be updated# 可以看到方法查询的顺序是先沿着superhero这条线到human,然后才是batprint(Batman.__mro__)# => (<class '__main__.Batman'>,# => <class 'superhero.Superhero'>,# => <class 'human.Human'>,# => <class 'bat.Bat'>, <class 'object'>)# Calls parent method but uses its own class attribute# 只有superhero有get_species方法print(sup.get_species())# => Superhuman# Calls overridden methodprint(sup.sing())# => nan nan nan nan nan batman!# Calls method from Human, because inheritance order matterssup.say('I agree')# => Sad Affleck: I agree# Call method that exists only in 2nd ancestor# 调用蝙蝠类的声呐方法print(sup.sonar())# => ))) ... (((# Inherited class attributesup.age = 100print(sup.age)# => 100# Inherited attribute from 2nd ancestor whose default value was overridden.print('Can I fly? ' + str(sup.fly)) # => Can I fly? False进阶生成器我们可以通过yield关键字创建一个生成器,每次我们调用的时候执行到yield关键字处则停止 。下次再次调用则还是从yield处开始往下执行:
# Generators help you make lazy code.def double_numbers(iterable):for i in iterable:yield i + i# Generators are memory-efficient because they only load the data needed to# process the next value in the iterable. This allows them to perform# operations on otherwise prohibitively large value ranges.# NOTE: `range` replaces `xrange` in Python 3.for i in double_numbers(range(1, 900000000)):# `range` is a generator.print(i)if i >= 30:break复制代码除了yield之外,我们还可以使用()小括号来生成一个生成器:
# Just as you can create a list comprehension, you can create generator# comprehensions as well.values = (-x for x in [1,2,3,4,5])for x in values:print(x)# prints -1 -2 -3 -4 -5 to console/terminal# You can also cast a generator comprehension directly to a list.values = (-x for x in [1,2,3,4,5])gen_to_list = list(values)print(gen_to_list)# => [-1, -2, -3, -4, -5]复制代码关于生成器和迭代器更多的内容,可以查看下面这篇文章:
五分钟带你弄懂迭代器与生成器,夯实代码能力
装饰器我们引入functools当中的wraps之后,可以创建一个装饰器 。装饰器可以在不修改函数内部代码的前提下,在外面包装一层其他的逻辑:
# Decorators# In this example `beg` wraps `say`. If say_please is True then it# will change the returned message.from functools import wrapsdef beg(target_function):@wraps(target_function)# 如果please为True,额外输出一句Please! I am poor :(def wrapper(*args, **kwargs):msg, say_please = target_function(*args, **kwargs)if say_please:return "{} {}".format(msg, "Please! I am poor :(")return msgreturn wrapper@begdef say(say_please=False):msg = "Can you buy me a beer?"return msg, say_pleaseprint(say())# Can you buy me a beer?print(say(say_please=True))# Can you buy me a beer? Please! I am poor :(复制代码装饰器之前也有专门的文章详细介绍,可以移步下面的传送门:
一文搞定Python装饰器,看完面试不再慌
结尾不知道有多少小伙伴可以看到结束,原作者的确非常厉害,把Python的基本操作基本上都囊括在里面了 。如果都能读懂并且理解的话,那么Python这门语言就算是入门了 。
 
如果你之前就有其他语言的语言基础,我想本文读完应该不用30分钟 。当然在30分钟内学会一门语言是不可能的,也不是我所提倡的 。但至少通过本文我们可以做到熟悉Python的语法,知道大概有哪些操作,剩下的就要我们亲自去写代码的时候去体会和运用了 。
根据我的经验,在学习一门新语言的前期,不停地查阅资料是免不了的 。希望本文可以作为你在使用Python时候的查阅文档 。

【万字干货,Python语法大合集,一篇文章带你入门】


推荐阅读