22

有趣的python

 5 years ago
source link: https://iweiyun.github.io/2018/11/12/python-interesting/?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
r = [x*x for x in range(1, 11)]
print(r)	# 输出:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

在Haskell中称为 List comprehension 的,写法与其类似:
[x*x | x <- [1..10]]

类型是小写的

# str即是表示字符串类型
def myFunc(s: str):
    # some code

参数类型是可选的,一般不需要加

与、或操作符,是用and、or来表示的

b1 = True
b2 = False
o1 = b1 and b2	# False
o2 = b1 or b2	# True

可以执行字符串

exec("print('Hello World')")	# 输出:Hello World

类似js中的 eval

列表可以从后面来访问

lst = [1, 2, 3]
print(lst[-1])	# 输出3, 也要注意不能越界

支持lambda表达式

lambda r, v : r + v

简单的交换变量的方式

x, y = y, x

类似swift的写法,本质都是利用元组来交换:
(x, y) = (y, x)

for-else结构

lst = [1, 3, 5, 7, 9, 13, 19]
for i in lst:
    if i % 2 == 0:
        print("找到了偶数")
        break
else:
    print("没有找到偶数")		# 输出:没有找到偶数

成员变量要在__init__里面指定,在方法外定义的是类属性

class Student(object):
    count = 0
    def __init__(self, name, score):
        self.name = name
        self.score = score
        Student.count += 1

m = Student("MMMM", 80)
print(Student.count)	# 1
print(m.name)	# MMMM

私有变量通过名字来限定

通过在名字前加双下划线,来表示是私有变量。

class Student(object):
    def __init__(self, name, score):
        self.__name = name
        self.__score = score

s = Student("Matthew", 60)
print(s.__name)	# 'Student' object has no attribute '__name'

类可以动态的增、删成员变量

class Student(object):
    pass

o = Student()
o.name = "Matthew"
print(o.name)	# 输出: Matthew

del o.name
print(o.name)	# 'Student' object has no attribute 'name'

js也有这个能力

调用不存在的属性,可以被开发者接管

class Student(object):
    def __getattr__(self, attr):
        if attr == 'name':
            return "Good"

o = Student()
print(o.name)	# 输出:Good

跟OC的转发找不到的方法非常像。包括 __str__ 方法,也非常类似OC中的 description ,来实现自定义打印内容

可以通过代码来设置断点

pdb.set_trace()

有点类似js的 debugger 语句


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK