做python面试题时遇到的问题

做python面试题时遇到的问题,理解有误之处多谢指正
原题:https://www.cnblogs.com/xiugeng/p/9712775.html
>>>30
s = dict.fromkeys(['A','B'],[])
s['B'].append('I')
print(s) # {'A': ['I'], 'B': ['I']}
said = id(s['A'])
sbid = id(s['B'])
print(said==sbid) # True
s['A'] = 'You'
print(s) # {'A': 'You', 'B': ['I']}
said = id(s['A'])
sbid = id(s['B'])
print(said==sbid) # False
------------------------
>>>>31
def num():
    temp = [lambda x:i*x for i in range(4)]
    print(temp)  # [<function num.<locals>.<listcomp>.<lambda> at 0x000002204FBB1820>,...]
    return temp  # lambda表达式
 
print([m(2) for m in num()])   # 列表生成式
我们设匿名函数为test,则展开结构如下
def num():
    L = []
    for i in range(4):
        def test(x): # 此方法不会在调用num()执行
            return x*i 
        L.append(test)
    return L
for m in num():
    print(m(2)) # 6,6,6,6
其实上例是一个典型的闭包陷阱,原因是返回的闭包函数中引用了会发生改变的变量i,导致不同实例共享了变量i
如果要使输出为[0,2,4,6],正确的闭包函数如下:
def num():
    L = []
    for i in range(4):
        def test(x,local_i=i):
            return x*local_i 
        L.append(test)
    return L
for m in num():
    print(m(2)) # 0,2,4,6
参考资料:https://www.cnblogs.com/liuq/p/6073855.html
        https://www.cnblogs.com/yssjun/p/9887239.html
-------------------------------
>>>>40
import math
print(math.sqrt(False+4)) # 2.0 
print(0.5 < True-0.4) # True 当bool进行算术运算时,会把True转为1,False转为0 
-----------------------
>>>>50
格式化字符串'{对应位置:格式化字符对齐方式总位数}'.format(第一位置填充字符,第二位置填充字符)
s = '{1:->10},{0:*<10}'.format(9,8) # ---------8,9*********
print(s)
------------------------
>>>>62 
class A(object):

    def __get__(self,obj,owner):
        print(self,obj,owner) # obj 实例所属直接对象,owner实例直接所属类
        return 'get被调用'

    def __set__(self,obj,val): # obj 实例所属直接对象,val接收参数
        print(obj,val)
        print('set被调用')
    
    def __delete__(self,obj): # obj 实例所属对象
        print('实例被删除:',obj)

class B(object):
    va = A()

b = B()
print(b.va) # <__main__.A object at 0x0000024D9FAE4880> <__main__.B object at 0x0000024D9FAE4130> <class '__main__.B'>get被调用
b.va='更新' # <__main__.B object at 0x0000024D9FAE4130> 更新
del(b.va) # 实例被删除: <__main__.B object at 0x0000024D9FAE4130>
class Person:
>>>>64
    def __init__(self,name='',age=0):
        self.name = name
        self.age = age
    @classmethod # 类和实例都可调用,实例一般不用此途径
    def getName(cls,name='nobody'): 
        return name
    def getAge(self): # 绑定到实例的方法,只有实例才能调用,否则报错
        return self.age
    @staticmethod # 类和实例都可调用 但不能通过常规self传参
    def outInfo(name,age):
        return '成功造出一个人:{}-{}'.format(name,age)
    @staticmethod
    def outInfo_(self):
        return '通过特殊方式造了一个人:{}-{}'.format(self.name,self.age)
print(Person.getName('Jack')) # Jack  ,类可以直接调用绑定到类的方法
print(Person.getAge(24)) # TypeError: getAge() missing 1 required positional argument: 'age'
p = Person('Jack',23)
print(p.getAge()) # 23
print(Person.outInfo('Tony',24)) # 成功造出一个人:Tony-24
print(p.outInfo_(p)) # 通过特殊方式造了一个人:Jack-23
参考链接:https://www.cnblogs.com/hyc123/p/11448685.html
>>>>70
import datetime
def timeLog(id):  # id == 装饰器参数 
    room = id
    def midwrapper(f):  # f == hello()
        def wrapper(*args): # *args == name
            print('welcome to NO.{} room'.format(room))
            print('{} called me'.format(f.__name__))
            f(*args)
            print(datetime.datetime.now())
        return wrapper
    return midwrapper

@timeLog(id=1)
def hello(name):
    print('hello {}'.format(name))
hello('Jack') 

# welcome to NO.1 room
# hello called me
# hello Jack
# 2020-08-17 15:17:13.509532
>>>>>74
class find_index:
    def __init__(self,numS,target):
        self.numS = numS
        self.target = target
    def outNum(self):
        for i in self.numS:
            j = self.target - i
            if j in self.numS and self.numS.index(j)>self.numS.index(i):
                print([self.numS.index(i),self.numS.index(j)])
c = find_index([2,7,11,15],9)
c.outNum() [0,1]
>>>>75
import json
a =json.dumps((1,2,3)) # 序列化支持元祖
print(type(a),a) # <class 'str'> [1, 2, 3] 这里自动把tuple转换为list了
b = json.loads(a)
print(type(b),b) # <class 'list'> [1, 2, 3]
c = json.loads('(1,2)') # json.decoder.JSONDecodeError: 不可以直接反序列化元祖
>>>>>80
def func(*args):
    for i in args:
        yield from i # == for j in i:
                     #       yield j

print(list(func([[1,2,3,4],[5,6,7,8]])))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值