几道练习题20200905

几道练习题20200905

github 几道练习题20200905

1

python可变对象不可变对象:
可变对象与不可变对象的区别在于对象本身是否可变。
可变对象:list、dict、set
不可变对象:typle、string、int、float、bool

2

a = [1,2,3,None,(),[],""]
print(len(a))

不管list里面是什么,都不会影响它的长度,所以是7

3

print(0xA +0xB + 0xc)

结果是33。这里考察的是十六进制。A-F表示10~15。

4

class parent:
    def __init__(self, param):
        self.v1 = param

class child(parent):
    def __init__(self, param):
        self.v2 = param

obj = child(100)
print('%d %d' % (obj.v1, obj.v2))

attribute error.
修改正确:

class child(parent):
    def __init__(self, param):
        # parent.__init__(self, param) # 调用父类的构造函数
        super().__init__(param) # 调用父类的构造函数
        self.v2 = param
  • super()函数

super() 函数是用于调用父类(超类)的一个方法。
super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。

5

class Account:
    def __init__(self, id):
        self.id = id
        id = 666
acc = Account(123)
print(acc.id)

结果:123

self.id 是实例变量,因此调用时,是__init__中的self.id=id 时赋的值,类初始化方法中id=666 为局部变量

6

import re
sentence = "we are humans"
matched = re.match(r"(.*)(.*?)(.*)", sentence)
print(matched.groups())

结果:('we are humans', '', '')

第一个(.*)是贪婪匹配,这样会把整个字符串都匹配到,后续两个正则就无法匹配到数据了

7

x = ["ab", "cd"]
for i in x:
    x.append(i.upper())

python3中会被kill掉,我认为是不停的循环自己然后不停的添加,陷入无限循环,占用系统资源越来越大,就被kill。
我自己测试了下,过然是这样,可以将该程序写入一个脚本(或者在ipython中执行),然后通过top命令观察进程所占资源的变化,我这里观察到,cpu,内存使用都接近百分之百,然后就被kill了。(可以在未被kill之前找到进程的进程号,然后通过top -p 进程号,只查看该进程的资源占用情况,这样比较直观)

8

for i in [1,2,3,4][::-1]:
    print(i)

4 3 2 1

考察的时python的切片操作

9

print("abcdefcdghcd".split("cd", 2))
print("abcdefcdghcd".split("cd", 1))

['ab', 'ef', 'ghcd']
['ab', 'efcdghcd']

第二个参数表示分割次数

10

class Count:
    def __init__(self, count = 0):
        self.__count = count
c1 = Count(2)
c2 = Count(2)
print(id(c1)==id(c2))
s1="good"
s2="good"
print(id(s1)==id(s2))

False True

s1 s2 指向同一内存空间。c1 c2时不同的实例对象

11

def f(x, l=[]):
    for i in range(x):
        l.append(i * i)
    print(l)
f(2)
f(3,[3,2,1])
f(3)

[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]

原文地址:https://www.cnblogs.com/liangping/p/13617380.html