原标题:千万不要错过这几道Python面试题
文末扫码领【python基础知识思维导图】
作者:梦想橡皮擦
来源:CSDN
话不多说,直接上题。
1
第一题
【修改以下Python代码,使得下面的代码调用类A的show方法?】
原始代码:
classA(object):
defrun(self):
print( "基础 run 方法")
classB(A):
defrun(self):
print( "衍生 run 方法 ")
obj = B
obj.run
修改代码:
classA(object):
defrun(self):
print( "基础 run 方法")
classB(A):
defrun(self):
print( "衍生 run 方法 ")
obj = B
obj.__class__ = A
obj.run
面试要点:
类继承,只要通过__class__方法指定类对象就可以了。
2
第二题
【修改以下Python代码,使得代码能够运行】
原始代码:
classA( object):
def__init__( self,a,b):
self.__a = a
self.__b = b
defshow( self):
print( "a=", self.__a, "b=", self.__b)
a = A( 5, 10)
a.show
a( 20)
修改代码:
classA( object):
def__init__( self,a,b):
self.__a = a
self.__b = b
defshow( self):
print( "a=", self.__a, "b=", self.__b)
def__call__( self, num):
print( "call:",num + self.__a)
a = A( 5, 10)
a.show
a( 20)
面试要点:
是方法对象,为了能让对象实例能被直接调用,需要实现__call__方法
3
第三题
【下面这段代码的输出是什么?】
原始代码:
classB(object):
def__init__(self):
print( "B init")
defrun(self):
print( "B run func")
classA(object):
defrun(self):
print( "A run func")
def__new__(cls, a):
print( "new",a)
ifa> 10:
returnsuper(A,cls).__new__(cls)
returnB
def__init__(self,a):
print( "init",a)
a1 = A( 5)
a1.run
a2 = A( 20)
这个运行需要对代码比较熟悉。
结果如下:
# a1 = A(5)
new5
B init
# a1.run
new5
B init
B run func
# a2 = A(20)
new5
B init
B run func
new20
init 20
4
第四题
【下面这段代码输出什么?】
原始代码:
num = 9
deffn1:
num = 20
deffn2:
print(num)
fn2 # 9
fn1 # 啥都没有
fn2 # 9
面试要点:
全局变量和局部变量。
num 不是个全局变量,所以每个函数都得到了自己的 num 拷贝,如果你想修改 num ,则必须用 global 关键字声明
5
第五题
【如何添加代码,使得没有定义的方法都调用myfunc方法?】
原始代码:
classA( object):
def__init__( self,a,b):
self.a1 = a
self.b1 = b
print( "初始化方法")
defmyfunc( self):
print( "myfunc")
a1 = A( 10, 20)
a1.fn1
a1.fn2
a1.fn3
修改代码:
classA( object):
def__init__( self,a,b):
self.a1 = a
self.b1 = b
print( "初始化方法")
defmyfunc( self):
print( "myfunc")
def__getattr__( self, item):
returnself.myfunc
a1 = A( 10, 20)
a1.fn1
a1.fn2
a1.fn3
面试要点:
python的默认方法, 只有当没有定义的方法调用时,才会调用方法 __getattr__。
当 fn1 方法传入参数时,我们可以给 myfunc方法增加一个 *args 不定参数来兼容。
本文为转载分享,侵删返回搜狐,查看更多
责任编辑: