python

    技术2022-07-12  76

    # 十进制 --》 二进制 bin(10) # 8进制 oct(10) #十六进制 hex(10) dic = {} dic = {'a': 1, 'b': 2} dic = dict(zip(['a', 'b'], [1,2])) dic = dict([('a',1),('b',2)]) # Out: {'a': 1, 'b': 1} # 切片 range(start, stop, step) a = [1,4,2,3,1] my_slice = slice(0,5,2) # 1,2,1 # tuple 将对象转为一个不可变的序列类型 a = [1,3,5] t = tuple(a) # 四舍五入 a = round(10.045, 2) # 返回对象内存大小 import sys a = {'a':1, 'b':2.0} big = sys.getsizeof(a) # 排序 a = [ {'name':'xiaoming', 'age':38, 'gender':'male'}, {'name':'xiaohong','age':20, 'gender':'female'} ] sorted(a, key=lambda x: x['age'], reverse=False) # 如果可迭代对象的所有元素都为真,那么返回 True,否则返回False all([1,0,3,6]) # False all([1,2,3]) # True #接受一个可迭代对象,如果可迭代对象里至少有一个元素为真,那么返回True,否则返回False any([0,0,0,[]]) # False any([0,0,1]) # True # 获取用户输入内容 input() print() print("i am {0},age {1}".format("tom",18)) print("{:+.2f}".format(-1)) # 带符号保留小数点后两位 print("{:.2%}".format(0.718)) # 百分比格式 print("{:.2e}".format(10241024)) # 指数记法 class C: def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x # 使用@property装饰器,实现与上完全一样的效果: class C: def __init__(self): self._x = None @property def x(self): return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x c = C() c._x = 1 c.setx(2) class Student(): def __init__(self, id,name): self.id = id self.name = name def __call__ (self): print('I am {} , id = {}'.format(self.name, self.id) ) xm = Student(1, 'xiaoming') xh = Student(id=2, name='xiaohong') # 是否可以调用 # 判断对象是否可被调用,能被调用的对象是一个callable 对象 callable(xm) # 如果 xm能被调用 , 需要重写Student类的__call__方法: xm() # I am xiaoming # 动态删除属性, 删除对象属性, hash 获取对象hash delattr(xm,'id') hasattr(xm, 'name') # True hash(xm.id) # 'Student' object has no attribute 'id' # 动态获取对象属性 getattr(xm, 'name') # 判断对象是否有这个属性 hasattr(xm, 'id') # 判断object是否为classinfo的实例,是返回true isinstance(xm, Student) class Undergraduate(Student): pass # 判断 Undergraduate 类是否为 Student 的子类 issubclass(Undergraduate, Student) """ 一键查看对象所有方法 不带参数时返回当前范围内的变量、方法和定义的类型列表; 带参数时返回参数的属性,方法列表。 """ dir(xm) """ ['__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name'] """

     

    Processed: 0.011, SQL: 9