python----异常、属性

三.异常


1.按自己方式出错


  • raise语句------引发异常

raise Exception引发一个没有任何错误的普通异常。后一个例子添加了hyperdrive overload错误信息。
  • 自定义异常类
             从Exception继承:cladd SomeCustomException(Exception): pass

2.捕捉异常


  • try/except实现
try:
    x=int(input('enter the first number: '))
    y=int(input('enter the second number: '))#input返回值为字符,int()强制转换
    print(x/y)
except ZeroDivisionError:
    print("The second number can't be zero!")
运行结果:

  • 传递异常
__metaclass__=type#确定使用新式类

class MuffledCalculator:
    muffled = False #true:开启屏蔽机制,false:关闭屏蔽机制
    def calc(self,expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if(self.muffled):
                print('Dividion by zero is illegal')
            else:
                raise
测试1:
calculator = MuffledCalculator()
print('the value of 10/2 is %f' %calculator.calc('10/2'))
运行结果:
测试2:
calculator = MuffledCalculator()
calculator.calc('10/0')#no muffled
运行结果:
测试3:
calculator = MuffledCalculator()
calculator.muffled=True
calculator.calc('10/0')#have muffled
运行结果:

  • 多个except子句
try:
    x=int(input('enter the first number: '))
    y=int(input('enter the second number: '))#input返回值为字符,int()强制转换
    print(x/y)
except ZeroDivisionError:
    print("The second number can't be zero!")
except ValueError:
    print("That wasn't a int number,was it ?")

测试结果:

  • 一个块捕捉两个异常
try:
    x=int(input('enter the first number: '))
    y=int(input('enter the second number: '))#input返回值为字符,int()强制转换
    print(x/y)
except (ZeroDivisionError,ValueError):
    print("hava exception")
测试结果:
  • 捕捉对象
try:
    x=int(input('enter the first number: '))
    y=int(input('enter the second number: '))#input返回值为字符,int()强制转换
    print(x/y)
except (ZeroDivisionError,ValueError) as e: #python3.x中写法 
    print(e)
测试结果:
  • 全捕捉
直接使用excpet
try:
    x=int(input('enter the first number: '))
    y=int(input('enter the second number: '))#input返回值为字符,int()强制转换
    print(x/y)
except:
    print("something wrong happen")
测试结果:

3.else子句


只有在没有异常引发的情况下才会执行
while True:
    try:
        x=int(input('enter the first number: '))
        y=int(input('enter the second number: '))#input返回值为字符,int()强制转换
        value = x/y
        print('x/y is ', value)
    except:
        print("something wrong happen,please try again")
    else:
        break

测试结果:


4.finally子句


不管try子句中是否发生异常,finally子句肯定会被执行

四.魔法(or特殊)方法、属性、迭代器


1.魔法方法


  • 构造方法__init__
    • 重写特殊的构造方法
                  如果一个类的构造方法被重写了,那么就需要调用超类(你所继承的类)的构造方法,否则对象可能不会被正确的初始化
例如:
__metaclass__=type#确定使用新式类
class Bird:
    def __init__(self):
        self.hungry = True
    def eat(self):
        if self.hungry:
            print("Aaaaaah.....")
            self.hungry=False
        else:
            print("No,thanks!")

class SongBird(Bird):
    def __init__(self):
        self.sound = 'I am a bird....'
    def sing(self):
            print(self.sound)
#测试超类Bird
print("Test class Bird:")
bird = Bird()
bird.eat()
print("After bird eats。。。。。")
bird.eat()
print()

print("Test class SongBird:")
#测试基类SongBird
songbird = SongBird()
songbird.sing()

测试结果:

如果执行songbird.eat(),结果:

在SongBird中,构造方法被重写,但新的构造方法没有任何关于初始化hungry特性的代码。
解决办法:
  • 调用超类构造方法的未绑定版本(旧版本Python,仅供了解)

SongBird类中只需要添加一行代码——Bird.__init__(self)。

class SongBird(Bird):
    def __init__(self):
        Bird.__init__(self)
        self.sound = 'I am a bird....'
    def sing(self):
            print(self.sound)

songbird = SongBird()
songbird.sing()
songbird.eat()
songbird.eat()

测试结果:


  • 使用super函数

super函数返回一个super对象,这个对象负责进行方法解析。当对其特性进行访问时,它会查找所有超类(以及超类的超类,直到找到特性为止,或者引发AtributeError异常)

class SongBird(Bird):
    def __init__(self):
        super(SongBird,self).__init__()
        self.sound = 'I am a bird....'
    def sing(self):
            print(self.sound)

songbird = SongBird()
songbird.sing()
songbird.eat()
songbird.eat()

测试结果:


  • 析构方法__del__,避免使用
  •  魔法方法集合

2.属性

  • property函数
__metaclass__=type#确定使用新式类
class Rectangle:
    def __init__(self):
        self.width=0
        self.height=0
    def setSize(self,size):
        self.width,self.height=size
    def getSize(self):
        return self.width,self.height
    size = property(getSize,setSize) #property函数创建了一个属性,访问器函数被作为参数,属性命名为size
    
r=Rectangle()
r.width=4
r.height=5
print("size is ",r.size)
print("after change size")
r.size=150,100
print("width is ", r.width)

测试结果:


  • 静态方法和类成员方法
    • 静态方法在创建时被装入Staticmethod类型的对象中,定义没有self参数,能够被类本身直接调用。
    • 类成员方法在创建时被装入Classmethod类型的对象中,定义时需要名为cls的类似于self的参数(自动绑定到类),可以直接用类的具体对象调用
使用@操作符,在方法的上方将装饰器列出

__metaclass__=type#确定使用新式类

class MyClass:
    
    @staticmethod
    def smethod():
        print("This is a static method")
    
    @classmethod
    def cmethod(cls):
        print("This is a class method of ",cls)
    
MyClass.smethod()
MyClass.cmethod()

运行结果:


3.迭代器


迭代器就是具有next方法(在调用时不需要任何参数)的对象。调用next方法,迭代器会返回它的下一个值。如果next被调用,但迭代器没有值可以返回,就会引发一个stopIteration异常。__iter__方法返回一个迭代器。(python3.x使用__next__而不是next)
一个实现了__iter__方法的对象是可迭代的,一个实现了next方法的对象则是迭代器

__metaclass__=type#确定使用新式类

class Fibs:
    def __init__(self):
        self.a=0
        self.b=1
    def __next__(self):
        self.a,self.b=self.b,self.a+self.b
        return self.a
    def __iter__(self):
        return self
    
fibs=Fibs()
for f in fibs:
    if(f>1000):
        print(f)
        break
    else:
        print("when f < 1000 ,the value of f is ",f)

运行结果:


4.生成器


未完!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
XPath是一种XML文档的定位方法,也可以用于HTML文档的定位,Selenium中也可以使用XPath来定位网页元素。下面是使用XPath定位元素的详细步骤: 1. 打开浏览器并访问网页: ```python from selenium import webdriver driver = webdriver.Chrome() driver.get("http://www.example.com") ``` 2. 使用XPath定位元素: ```python # 通过元素id定位 element = driver.find_element_by_xpath('//*[@id="element_id"]') # 通过元素name定位 element = driver.find_element_by_xpath('//*[@name="element_name"]') # 通过元素class定位 element = driver.find_element_by_xpath('//*[@class="element_class"]') # 通过元素标签名定位 element = driver.find_element_by_xpath('//tag_name') # 通过元素属性定位 element = driver.find_element_by_xpath('//*[@attribute_name="attribute_value"]') # 通过元素文本内容定位 element = driver.find_element_by_xpath('//*[text()="text_content"]') # 通过元素部分文本内容定位 element = driver.find_element_by_xpath('//*[contains(text(), "text_content")]') ``` 3. 对元素进行操作: ```python # 输入文本 element.send_keys("text_input") # 点击元素 element.click() # 获取元素文本 print(element.text) # 获取元素属性值 print(element.get_attribute("attribute_name")) ``` 注意事项: - XPath定位需要用到浏览器的开发者工具,在开发者工具中可以查看元素的XPath路径。 - XPath路径中的引号需要用不同类型的引号包裹,例如在单引号内使用双引号包裹。 - 如果XPath路径中包含斜杠(/),则需要使用双斜杠(//)或者使用单引号包裹整个XPath路径。 - 在XPath路径中没有找到元素时,会抛出NoSuchElementException异常

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值