python随笔day03

zlik8991 / 2024-07-08 / 原文

python面试基础问题

  1. lambda表达式
    基本语法:
变量 = lambda [参数列表]:表达式(函数代码+返回值)
#调用
变量()
例子如下:
#加法求和函数
a = lambda a, b : a+b
print(a(1,2))#3

#args元组类型
b = lambda *args : args
print(b('a','b','c','d',10))#('a', 'b', 'c', 'd', 10)

#**kw
c = lambda **kwargs : kwargs
print(c(name = '张三',age = 29))#{'name': '张三', 'age': 29}

2.局部函数

在函数里面定义的函数就是局部函数。

#局部函数,解决遮蔽问题用nonlocal修饰
def test():
    str = "hello"
    def test01():
        str = "world"
        print(str)
    test01()


test()#world  

# 修饰后
def test02():
    str = "hello"
    def test03():
        nonlocal str#修饰局部变量,使得局部变量str指向外部的str变量
        print(str)
        str = "world"
        # print(str)
    test03()

test02()#hello

3.闭包

a.nonlocal主要是在嵌套函数中访问并修改外层函数(非全局)作用域的变量。

b.在函数嵌套的前提下,内部函数使用了外部函数的变量,并且外部函数返回了内部函数,我们把这个使用外部函数变量的内部函数称为闭包函数。

c.特点:

(1)闭包函数的特点是可以访问和修改其所在作用域中的变量,即使这些变量在函数外部已经不可见或作用域已经结束。

(2)闭包函数可以延长变量的生命周期,使得函数在定义时的上下文信息能够被保留下来,并在需要时被使用。

(3)这种特性使得闭包在某些情况下非常有用,比如在函数式编程、回调函数等场景中。

闭包示例:

def outer_function(x):  
    def inner_function(y):
        nonlocal x #修饰外部函数中的变量x
        x=10
        return x + y
    return inner_function

closure = outer_function(20 )
result = closure(9)  # 这里的闭包函数引用了外部函数中的变量x
print(result)  # 输出:19

4.求一个整数,他加上100后是一个完全平方数,再加上268又是一个完全平方数?

#判断是否是完全平方数
def square(n):
    return (int(n**0.5)**2 == n)

def find_number():
    for i in range(10000):#可以修改范围
        if square(i+100) and square(i+100+268):
            return i
    return None

result = find_number()
if result is not None:
    print(f"满足条件的整数是: {result}")
else:
    print("没有找到满足条件的整数。")

5.下面程序会输出的结果是__main__

__name__ 是一个特殊变量,它代表当前模块的名字。在一个脚本中直接运行代码时,该脚本的 __name__ 值会被设置为 "__main__"

例1:

class Person:
    def __init__(self):
        pass
    def getAge(self):
        print (__name__)

p = Person()
p.getAge()#__main__

例2:

# 文件:person.py  
class Person:  
    def __init__(self):  
        pass  
    def getAge(self):  
        print(__name__)  
  
# 文件:main.py  
from person import Person  
  
p = Person()  
p.getAge()  # 这里将输出 "person",因为 person.py 的 __name__ 是 "person"

6.执行下面代码,不会报错异常的是?

#1
class Rect:
    def __init__(self, width, height):
        self.width = width
        self.height = height
    @property
    def area(self):
        return self.width * self.height
  
rect = Rect(5, 10)
print(rect.area) # 50

#2
a =0 
def fun():
    a+=1
    print(a)
fun() 
#异常UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
#3
class A:
    def __init__(self,color = "red"):
        A.color = color
    def printColor(self):
        print(A.color)

class B(A):
    def __init__(self):
        pass

b = B()
b.printColor() #异常type object 'A' has no attribute 'color'
#4
class D:
    def __init__(self,color="red"):
        self.__color = color

d = D()
print(d.__color) #'D' object has no attribute '__color'. Did you mean: '_D__color'?

7.文件的备份功能

需要导入模块os

编号 函数 功能
1 os.mkdir(新文件夹名称) 创建一个指定名称的文件夹
2 os.getcwd() current work directory,获取当前目录名称
3 os.chdir(切换后目录名称) change directory,切换目录
4 os.listdir(目标目录) 获取指定目录下的文件信息,返回列表
5 os.rmdir(目标目录) 用于删除一个指定名称的"空"文件夹
6 os.path.basename(file_path) 拆分路径获得文件名
7 os.path.dirname(file_path) 拆分路径获得文件目录
#文件备份功能
import os
import shutil

# 备份文件
def backup_file(file_path): 
    # 获取文件名
    file_name = os.path.basename(file_path)
    print('正在备份文件:', file_name)
    # 获取文件目录
    file_dir = os.path.dirname(file_path)
    print('文件目录:', file_dir)
    #获取文件后缀名
    index = file_name.rfind('.')
    first_name = file_name[:index]
    last_name = file_name[index:]
    # 备份文件名
    backup_file_name = first_name + '[备份]'+ last_name
    # 备份文件路径
    backup_file_path = os.path.join(file_dir, backup_file_name)
    # 备份文件
    shutil.copy(file_path, backup_file_path)
    print('文件已备份至:', backup_file_path)

# 主函数
if __name__ == '__main__':
    file_path = input('请输入要备份的文件路径:')# 输入要备份的文件路径
    if not os.path.exists(file_path):
        print('文件不存在!')
        exit()
    else:
        backup_file(file_path)

8.面向过程和面向对象的区别?

① 都可以实现代码重用和模块化编程,面向对象的模块化更深,数据也更封闭和安全;

② 面向对象的思维方式更加贴近现实生活,更容易解决大型的复杂的业务逻辑;

③ 从前期开发的角度来看,面向对象比面向过程要更复杂,但是从维护和扩展的角度来看,面向对象要远比面向过程简单;

④ 面向过程的代码执行效率比面向对象高。

9.那些意想不到的结果(小菜)

a = range(100)
print(a[-3])#97
print(a[2-3])#99
print(a[::3])#range(0, 100, 3)
print(a[2:13])#range(2, 13)

10.字符串index()方法

字符串(String)的 index()方法用于查找子字符串(子串)在主字符串中首次出现的位置(索引)。如果找到了子字符串,则该方法返回子字符串第一次出现的索引;如果没有找到,则抛出一个 ValueError异常。

str1 = "hello world"
str2 = "world"
print(str1.index(str2))#6 找到返回索引值,没找到会报错