Python面试题

1.解释类方法、静态方法

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.

@staticmethod means: when this method is called, we don’t pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can’t access the instance of that class (this is useful when your method does not use the instance).

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

class Animal(object):
    def foo(self,x):
        print(self,x)

    @staticmethod
    def static_foo(x):
        print(x)

    @classmethod
    def class_foo(cls,x):
        print(cls,x)


a = Animal()
a.foo(1)             # 调用一般方法
Animal.static_foo(1) # 调用静态方法
Animal.class_foo(1)  # 调用类方法

2.书写一个函数,用于替换某个字符串或几个字符串

函数原型strreplace(str,oldString,newString)
例如:

>>s = 'Hello World!';
>>afterReplace = strreplace(s,'World','Tom')
输出结果为:"Hello Tom!"

代码实现:

def strreplace(str,oldString,newString):
        str_list = str.split(oldString)
        print(newString.join(str_list))

strrepalce('Hello World !','World','Tom')

3.遍历查找指定后缀文件

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

# 1. for-in dir/subdir to get the filesname
# 2. splitext filename to filter

import os

def getFiles(dir, suffix): # 查找根目录,文件后缀 
    res = []
    for root, directory, files in os.walk(dir):  # =>当前根,根下目录,目录下的文件
        for filename in files:
            name, suf = os.path.splitext(filename) # =>文件名,文件后缀
            if suf == suffix:
                res.append(os.path.join(root, filename)) # =>吧一串字符串组合成路径
    return res

for file in getFiles("./", '.py'):  # =>查找以.py结尾的文件
    print(file)

4.实现删除一个list里面的重复元素(元素顺序并不改变)

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

a = "aAsmr3idd4bgs7Dlsf9eAF"
a_list = list(a)  # 转化为列表,并保存元素顺序
set_list = list(set(a_list))  # 去重
set_list.sort(key=a_list.index)
s = ''.join(set_list)
print(s)

5.实现分组一个 list 里面的元素,比如 [1,2,3,…100]变成 [[1,2,3],[4,5,6]….]

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
list = []
list_temp =[]
for l in (x for x in range(1,101)):
    list_temp.append(l)
    if len(list_temp)==3:
        list.append(list_temp)
        del list_temp
        list_temp = []
print(list)

6.写出一个函数,给定参数 n,生成含有 n 个元素值为 1~n 的数 组,元素顺序随机,但值不重复

import random

def random_list(n):
    list =random.sample(range(1,n+1),n)
    return list

print(random_list(6))

7.在不用其他变量的情况下,交换a、b变量的值

# pyhton
a,b = b,a

# 其他语言
a = a + b
b = a - b
a = a - b

8.写出下面代码的输出结果

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

def extend_list(val,list = []):
    list.append(val)
    return list

list1 = extend_list(10)
list2 = extend_list(123, ['a', 'b', 'c'])
list3 = extend_list('a')

print('list1:',list1)
print('list2:',list2)
print('list3:',list3)

print(hex(id(list1)))
print(hex(id(list2)))
print(hex(id(list3)))

输出结果:

list1: [10, 'a']
list2: ['a', 'b', 'c', 123]
list3: [10, 'a']
0x17356fb8648   #
0x17356fb8d08
0x17356fb8648   #list1和list2 内存地址相同

9. 说明os,sys模块不同,并列举常用的模块方法?

官方解释:
os: This module provides a portable way of using operating system dependent functionality.
翻译:提供一种方便的使用操作系统函数的方法。
sys:This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
翻译:提供访问由解释器使用或维护的变量和在与解释器交互使用到的函数。

os 常用方法

方法使用
os.remove()删除文件
os.rename()重命名文件
os.walk()生成目录树下的所有文件名
os.chdir()改变目录
os.mkdir/makedirs创建目录/多层目录
os.rmdir/removedirs删除目录/多层目录
os.listdir()列出指定目录的文件
os.getcwd()取得当前工作目录
os.chmod()改变目录权限
os.path.basename()去掉目录路径,返回文件名
os.path.dirname()去掉文件名,返回目录路径
os.path.join()将分离的各部分组合成一个路径名
os.path.split()返回(dirname(),basename())元组
os.path.splitext()(返回filename,extension)元组
os.path.getatime\ctime\mtime分别返回最近访问、创建、修改时间
os.path.getsize()返回文件大小
os.path.exists()是否存在
os.path.isabs()是否为绝对路径
os.path.isdir()是否为目录
os.path.isfile()是否为文件

sys 常用方法

方法使用
sys.argv()命令行参数List,第一个元素是程序本身路径
sys.modules.keys()返回所有已经导入的模块列表
sys.exc_info()获取当前正在处理的异常类,exc_type、exc_value、exc_traceback当前处理的异常详细信息
sys.exit(n)退出程序,正常退出时exit(0)
sys.hexversion获取Python解释程序的版本值,16进制格式如:0x020403F0
sys.version获取Python解释程序的版本信息
sys.maxint最大的Int值
sys.maxunicode最大的Unicode值
sys.modules返回系统导入的模块字段,key是模块名,value是模块
sys.path返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform返回操作系统平台名称
sys.stdout标准输出
sys.stdin标准输入
sys.stderr错误输出
sys.exc_clear()用来清除当前线程所出现的当前的或最近的错误信息
sys.exec_prefix返回平台独立的python文件安装的位置
sys.byteorder本地字节规则的指示器,big-endian平台的值是’big’,little-endian平台的值是’little’
sys.copyright记录python版权相关的东西
sys.api_version解释器的C的API版本
sys.getdefaultencoding()返回当前你所用的默认的字符编码格式
sys.getfilesystemencoding()返回将Unicode文件名转换成系统文件名的编码的名字
sys.setdefaultencoding(name)用来设置当前默认的字符编码,如果name和任何一个可用的编码都不匹配,抛出 LookupError,这个函数只会被site模块的sitecustomize
sys.builtin_module_namesPython解释器导入的模块列表
sys.executablePython解释程序路径
sys.getwindowsversion()获取Windows的版本
sys.stdin.readline()从标准输入读一行,sys.stdout.write(“a”) 屏幕输出a
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值