TypeError ‘str‘ object is not callable 问题的解决方法

  • Post author:
  • Post category:其他


最近在学习自动化测试,使用的是selenium+pytest自动化测试框架,对selenium api封装,运行时报了

TypeError 'str' object is not callable


在这里插入图片描述

‘str’ object is not callable 一般出现在企图调用一个不可被调用的对象。

其实 pycharm 已经将有问题的代码做了下划线标注啦。

通过阅读selenium api文档发现,一些属性(或者方法)是可以调用的,另外一些不可以调用,可以调用的属性是以圆括号结尾的。

下面是属性的一个例子: * current_url 当前载入页面的URL

使用:

driver.current_url

下面是方法的一个例子 * close()

关闭当前窗口 使用:

driver.close()

所以要认真阅读文档才能避免一些不必要的错误 。

但是要想

driver.current_url

能被调用怎么办呢,经常我不懈的努力,终于找到了一个非常好的解决方法,那就是@property !

@property是Python内置的装饰器。它的作用是:将方法变成属性调用。


使用场景:


1.修饰方法,使方法可以像属性一样访问。

class DataSet(object):
  @property
  def method_with_property(self): ##含有@property
      return 25
  def method_without_property(self): ##不含@property
      return 25

l = DataSet()
print(l.method_with_property) # 加了@property后,可以用调用属性的形式来调用方法,后面不需要加()。
print(l.method_without_property())  #没有加@property , 必须使用正常的调用方法的形式,即在后面加()

2.与所定义的属性配合使用,这样可以防止属性被修改。

​ 由于python进行属性的定义时,没办法设置私有属性,因此要通过@property的方法来进行设置。这样可以隐藏属性名,让用户进行使用的时候无法随意修改。

class Rectangle(object):
  @property
  def width(self):
    # 变量名不与方法名重复,改为_width,下同
    return self._width
  @width.setter
  def width(self, value):
    self._width = value
  @property
  def height(self):
    return self._height
  @height.setter
  #与property定义的方法名要一致
  def height(self, value):
    self._height = value
  @property
  def resolution(self):
    return self._width * self._height
s = Rectangle()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
    print('测试通过!')
else:
    print('测试失败!')



版权声明:本文为BaiXuePrincess原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。