赞
踩
import sys from selenium.common import ElementClickInterceptedException """ 列表 """ spam = ['cat', 'bat', 'rat', 'elephant'] # 删除列表元素 del spam[2] #列表升序排列 spam.sort() spam.sort(reverse=True) #降序排列 spam.reverse() #列表反转 # for a in spam: # print(a) # 切片 左闭右开 print(spam[-1]) # elephant print(spam[1:4]) # ['bat', 'rat', 'elephant'] print(spam[0:-1]) # ['cat', 'bat', 'rat'] print(spam[:2]) # ['cat', 'bat'] print(spam[1:]) # ['bat', 'rat', 'elephant'] print(spam[:]) # ['cat', 'bat', 'rat', 'elephant'] print(len(spam)) # 4 # 异常处理 try: print(spam[4]) except OSError as err: print("OS error: {0}".format(err)) except IndexError: print("array out of bounds.") except: print("Unexpected error:", sys.exc_info()[0]) raise # 列表连接和列表复制 print([1, 2, 3] + ['A', 'B', 'C']) # [1, 2, 3, 'A', 'B', 'C'] print(['X', 'Y', 'Z'] * 3) # ['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z'] spam = [1, 2, 3] spam = spam + ['A', 'B', 'C'] print(spam) # [1, 2, 3, 'A', 'B', 'C'] del spam[2] # 删除 ’3‘ [1, 2, 'A', 'B', 'C'] print(spam) # 多重赋值技巧 cat = ['fat', 'black', 'loud'] size, color, disposition = cat # 字典和结构化数据 (1)字典中的表项是不排序的 (2)不能像列表那样切片 spam = {12345: 'Luggage Combination', 42: 'The Answer'} spam = {'name': 'Zophie', 'age': 7} print(spam.keys()) # dict_keys(['name', 'age']) list(spam.keys()) # ['name', 'age'] print(spam.values()) print(spam.items()) print(spam.get('birthday', '1998')) # 1998 spam.clear() #清空字典 #遍历 for k,v in spam.items(): print(k,v) spam = {'name': 'Pooka', 'age': 5} spam.setdefault('color', 'black') # setdefault()方法提供了一种方式,在一行中完成这件事。传递给该方法的第一个参数,是要检查的键。第二个参数,是如果该键不存在时要设置的值。如果该键确实存在,方法就会返回键的值。在交互式环境中输入以下代码: try: spam['age'] except ElementClickInterceptedException as error: print(error) # color except: print("Unexpected error:", sys.exc_info()[0]) raise # raise [Exception [, args [, traceback]]] else: print("没有异常时执行的代码") finally: print('这句话,无论异常是否发生都会执行。') def spam(): global catNames catNames = [] while True: print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to stop.):') name = input() if name == '': break catNames = catNames + [name] # list concatenation print('The cat names are:') for name in catNames: print(' ' + name) # 字符串方法 join()和split() strqq = ', '.join(['cats', 'rats', 'bats']) # 传入一个列表值 print(strqq) # cats, rats, bats list_01 = 'MyABCnameABCisABCSimon'.split('ABC') # 默认按照各种空白字符分割,诸如空格、制表符或换行符。这些空白字符不包含在返回列表的字符串中,传值后按照字符串分割 print(list_01) # ['My', 'name', 'is', 'Simon'] # 列表链接 aaa = [1, 2, 3] ';'.join([str(a) for a in aaa]) # 1;2;3 # 用rjust()、ljust()和center()方法对齐文本 def printPicnic(itemsDict, leftWidth, rightWidth): print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-')) for k, v in itemsDict.items(): print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth)) # copy.copy(spam) # 用strip()、rstrip()和lstrip()删除空白字符 if __name__ == '__main__': # spam() # print(catNames) # catNames.pop() # 删除并返回索引处的项目(默认最后一个) tuple(['cat', 'dog', 5]) # ('cat', 'dog', 5) list(('cat', 'dog', 5)) # ['cat', 'dog', 5] list('hello') # ['h', 'e', 'l', 'l', 'o'] picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000} printPicnic(picnicItems, 12, 5) printPicnic(picnicItems, 20, 6)
# !/user/bin python3 # -*- coding: utf-8 -*- class Car(object): num = 111 # 定义类的方法时,第一个参数必须是self,self参数代表将来要创建的对象本身 def info(self): print("This is a car") if __name__ == '__main__': # 实例化类 car = Car() print("Car类对象的属性 num 为:", car.num) car.info() # 类属性属于类本身,可通过类名和对象进行访问和修改 Car.num = 222 print("Car类对象的属性 num 为:", Car.num)
# !/user/bin python3 # -*- coding: utf-8 -*- """ python中类的构造函数是__init__(),一般用来为类的属性设置初值或进行其他必要的初始化工作 """ class People(object): # 定义构造方法 def __init__(self, name, gender): # 定义属性 self.name = name self.gender = gender # 功能函数1() def speak(self): """people can speak""" print(f"{self.name}的性别是{self.gender}") if __name__ == '__main__': # 初始化对象 people = People("Tom", "Male") people.speak() # 通过类的对象访问实例属性,类的实例属性可以被类的对象访问和修改 people.name = 'Jim' people.gender = 'female' people.speak()
# !/user/bin python3 # -*- coding: utf-8 -*- """ 子类可以通过继承父类,享有父类所有的属性和方法。在python中支持类的单继承和多继承 """ class People(object): # 定义构造方法 def __init__(self, name, gender): # 定义属性 self.name = name self.gender = gender # 功能函数1() def speak(self): """people can speak""" print(f"{self.name}的性别是{self.gender}") class Stdent(People): def __init__(self, name, gender, grade): super().__init__(name, gender) self.grade = grade def info(self): print(f"{self.name}说:我的性别是{self.gender},在读{self.grade}年级。") def speak(self): """子类对父类方法的重写""" super().speak() print(f"{self.name}说:我的性别是{self.gender},在读{self.grade}年级。") if __name__ == '__main__': stu = Stdent("Tom", "male", 3) stu.speak() stu.info()
# !/user/bin python3 # -*- coding: utf-8 -*- """ 子类可以通过继承父类,享有父类所有的属性和方法。在python中支持类的单继承和多继承 """ # 定义父类 class Animal1: # 定义构造方法 def __init__(self): # 定义属性 print("creating an animal1") # 功能函数1 def run(self): print("running...") # 功能函数2 def jump(self): print("jump from Animai1") # 定义父类 class Animal2: # 定义构造方法 def __init__(self): # 定义属性 print("creating an animal2") # 功能函数1 def eat(self): print("eating...") # 功能函数2 def jump(self): print("jump from Animal2") # 定义子类继承两个父类 class Pig(Animal1, Animal2): def __init__(self): print("creating a pig") def cry(self): print("crying ...") if __name__ == '__main__': pig = Pig() pig.cry() pig.eat() # 在Pig类中调用父类的jump()方法时,按照多继承的从左到右的顺序,调用方法 pig.jump()
# !/user/bin python3 # -*- coding: utf-8 -*- """ 让类的属性不能被外部访问,可以在属性的名称前加上两个下划线"__" """ class Student(object): def __init__(self, name, age): # 属性前加两个下划线"__",变成了私有属性 self.__name = name self.__age = age def __info(self): print(f"{self.__name},{self.__age}") def getname(self): return self.__name def getinfo(self): self.__info() if __name__ == '__main__': stu = Student("Tom", 21) stu.getinfo() print(stu.getname())
# !/user/bin python3 # -*- coding: utf-8 -*- """ 让类的属性不能被外部访问,可以在属性的名称前加上两个下划线"__" """ class Student(object): # 属性限制 # __slots__ = ("_Student__name", "_Student__age") def __init__(self, name, age): # 属性前加两个下划线"__",变成了私有属性 self.__name = name self.__age = age def __info(self): print(f"{self.__name},{self.__age}") def getname(self): return self.__name def getinfo(self): self.__info() def __call__(self,first,*args, **kwargs): print(f"打印__call__()方法的参数 *args={first}") print(f"打印__call__()方法的参数 *args={[v for v in args]}") # print(f"打印__call__()方法的参数 *kwargs={for k,v in kwargs.items()}") print(';'.join([str(v) for v in args])) if __name__ == '__main__': stu = Student("Tom", 21) print(stu.__dict__) print(('name=', stu.__dict__['_Student__name'])) print(('age=', stu.__dict__['_Student__age'])) args = ("1","2","3","4","5") kwargs = {"arg3": 3, "arg2": "two", "arg1": 5} stu(1, 2, 3, 4, y=1, a=2, b=3, c=4)
# !/user/bin python3 # -*- coding: utf-8 -*- """ 静态方法是类中的函数,不需要实例。 静态方法主要用来存放逻辑性的代码,和类本身没有交互 静态方法不会涉及类中的方法和属性的操作 静态方法可以通过类名访问,也可以通过实例访问 静态方法定义的时候使用@staticmethod装饰器 """ class Car(object): @staticmethod def description(): print("This is a car.") if __name__ == '__main__': c1 = Car() c1.description() Car.description() c1.__dict__
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。