1.简述read、readline、readlines的区别
同:使用变量用于限制每次读取的数据量
read:从文件当前位置读取size个字节,若无size,则表示读取至文件结束位置,返回字符串对象
readline:每次只会读取一行,返回字符串对象
readlins:是一次性把内容完全读取出来,读取所有行,返回列表。
拓展:输出文件的某一行
line = linecache.getline(‘txt.txt’,2)
2.创建字典的至少两种方法
dic1 = {'name': 'Allen', 'age': 21, 'gender': 'male'}
dic2 = {}
dic2['name'] = 'Allen'
dic3 = dict(name='Allen', age=14, gender='male')
dic4 = dict([('name', 'Allen'), ('age', 21), ('gender', 'male')])
dic5 = dict({'one': 1, 'two': 2, 'three': 3})
list1 = ["A", "B"]
list2 = ["a", "b"]
dic6 = dict(zip(list1, list2))
print(dic1, dic2, dic3, dic4, dic5, dic6)
3.用yield写一个生成器
可迭代对象需要实现iter方法
迭代器不仅要实现iter方法,还需要实现next方法
可迭代对象迭代器:通过python内置的iter函数,就能实现next方法
生成器-yield
在python中一个函数可以用yield代替return返回值,这样函数就会变成生成器对象
list=[1,2,3,4,5] list=iter(list) print(next(list)) ----------------------------- def generator(array): for i in array: return i gen = generator([1,2,3,4,5]) print(type(gen)) 输出:------------------------------ def generator(array): for i in array: yield(i) gen = generator([1,2,3,4,5]) print(type(gen)) 输出:
4.编写一段代码,列出26个字母的大小写组合
import string words1 = string.ascii_lowercase print(words1) words2 = list(string.ascii_uppercase) print(words2) words3 = list(string.ascii_letters) print(words3)
5.python装饰器
闭包函数:内部函数引用外部函数定义的对象(主要满足2点:函数内部定义的函数;引用了外部变量但非全局变量),闭包可以将其自己的代码和作用域以及外部函数的作用结合在一起注意点:内嵌函数只可以在外部函数的作用域内被正常调用,在外部函数的作用域之外调用会报错
简单的例子
def count():
a = 1
b = 2
def num():
c = 3
d = a + c
return d
return num
python装饰器
python装饰器本质上就是一个函数,它可以让其他函数再不需要做任何代码变动的前提下增加额外的功能,装饰器的返回值也是一个函数对象(函数的指针)
实质: 是一个函数
参数:是你要装饰的函数名(并非函数调用)
返回:是装饰完的函数名(也非函数调用)
作用:为已经存在的对象添加额外的功能
特点:不需要对对象做任何的代码上的变动
import time
import time
def decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
func()
end_time = time.time()
print(end_time - start_time)
return wrapper
@decorator
def func():
time.sleep(0.8)
func()
5.@classmethod、@staticmethod、@property的含义
同:一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法
@staticmethod或者classmethod,就可以不需要实例化,直接类名.方法名()来调用异:@staticmethod不需要表示自身对象的seld和自身类的cls参数,就跟使用函数一样
@classmethod也不需要self参数,但第一个参数需要表示自身类的cls参数@property把一个方法变成一个静态属性
@property属性方法 封装类中的方法,给用户更加简单的调用方式,隐藏具体的实现细节。@method.getter 获取属性@method.setter 设置属性, 可以写更多逻辑(比如格式转换,类型判断),并提醒其他人这里面可能有magic
@method.deleter 删除属性
class A(object):
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
if isinstance(value, str):
self.__name = value
else:
raise TypeError("%s must be str" % value)
@name.deleter
def name(self):
raise AttributeError("can not be delete")
a = A("alex")
print(a.name)
a.name = 222
del a.name
@staticmethod
import time
class Date(object):
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@staticmethod
def now():
t = time.localtime()
return Date(t.tm_year, t.tm_mon, t.tm_mday)
date = Date.now()
print(date.year, date.month, date.day)
date = Date(1999,12,12)
@classmethod
class ParentClass(object):
var = "test for parent"
@classmethod
def clsmethod(cls):
print(cls.var)
class SubClass(ParentClass):
var = "test for sub"
ParentClass.clsmethod()
>>>
test for parent
SubClass.clsmethod()
>>>
test for sub
Classmethod主要用途是作为构造函数;
Python只有一个构造函数__new__,如果想要多种构造函数就很不方便。只能在new里面写一堆if isinstance 。
有classmethod之后就可以用classmethod来写不同的构造函数,cpython里面大部分classmethod最后都是 return cls(XXX), return XXX.new ()之类的。Staticmethod主要用途是限定Namespace;
也就是说这个函数虽然是个普通的function,但是它只有这个class会用到,不适合作为module level的function,这时候就把它作为staticmethod。
如果不考虑namespace的问题的话直接在module里面def function就行了。
6.逻辑运算符
优先级:() > not > and > or
or:x or y, 如果x为True则返回x,如果x为False返回y值and:x and y ,如果x为True则返回y,如果x为False返回x值print(1 > 2 and 3 or 4 and 3 < 2 or not 4 > 5)
7.利用python内置方法求差集、交集、并集
a = [1,2,3] b = [1,2] print(list(set(a) | set(b))) 并集 print(list(set(a) - set(b))) 交集 print(list(set(a) ^ set(b))) 差集
8.python字典和json字符串相互转化方法
字典转json:json.dumps()
json转字典:json.loads()
9.什么是lambda函数
num = lambda x: x + 1
print(num(1))
10.python2和python3区别?列举5个
1.python2既可以使用带小括号的方式,也可以使用一个空格来分隔打印内容
python3使用print必须要以小括号包裹打印内容2.python2中使用ascii编码,python3中使用utf-8编码3.python2中unicode表示字符串序列,str表示字节序列。python3中str表示字符串序列,byte表示字节序列4.python2中为正常显示中文,引入coding声明,python3中不需要。5.python2中是raw_input()函数,python3中是input()函数。



