Representation Strings 一个是Python表达式(解释器可以直接运行的形式),一个是字符串(人类可读的形式)
repr 1 2 3 4 5 6 >>> s = 'hello' >>> print(repr(s)) 'hello' >>> repr(min) '<built-in function min>' str 1 2 3 4 5 6 7 8 >>> from fractions import Fraction >>> half = Fraction(1, 2) >>> print(half) # calls __str__ 1/2 >>> repr(half) # calls __repr__ 'Fraction(1, 2)' >>> eval(repr(half)) # creates a new Fraction object Fraction(1, 2) F-Strings { }里面的按照表达式来计算
1 2 3 4 >>> x = 10 >>> y = 20 >>> f"x + y = {x + y}" 'x + y = 30' 多态函数 Functions that apply to many different forms of data…
Generators a kind of special iterator!
yield 1 2 3 4 5 6 7 8 9 10 def count_to(n): for i in range(n): yield i for i in count_to(5): print(i) t = count_to(5) # t is like a generator object at <generator object count_to at 0x000001> print(next(t)) Generator vs Iterator yield from is a new syntax in Python 3.3 that allows you to delegate iteration to another generator.
1 2 3 4 5 6 7 8 9 def countdown(k): if k > 0: yield k yield from countdown(k-1) # element-wise iteration of the sub-generator for i in countdown(5): print(i) list(countdown(5)) # [5, 4, 3, 2, 1] Example:
Object-Oriented Programming class 1 2 3 4 5 6 7 8 9 10 11 12 class MyClass: def __init__(self, x, y): # constructor # instance variables self.x = x self.y = y def my_method(self): # non-static method print(self.x, self.y) @staticmethod def my_static_method(x, y): # static method print(x, y) Python uses dynamic typing…… 😋
Binding an object to a new name does not create a new object. It creates a new reference to the same object.