【问题标题】:Python: string test not evaluatingPython:字符串测试未评估
【发布时间】:2021-11-25 06:07:55
【问题描述】:

我正在尝试做应该是简单的字符串比较,但我无法让它工作:

class Bonk:
  def __init__(self, thing):
    self.thing = thing

  def test(self):
    if self.thing == 'flarn':
      return 'you have flarn'
    return 'you have nothing'

bonk1 = Bonk('glurm')
bonk2 = Bonk('flarn')

bonk1.test()
bonk2.test()

这会返回nothing。我也试过这个:

def test(self):
  if self.thing in ['flarn']:
    ...

这也不起作用。

我尝试了双引号,将“flarn”分配给一个变量,然后针对该变量进行测试,在列表测试的末尾添加一个逗号。我尝试将其作为变量传递...但没有任何效果。

我错过了什么?

【问题讨论】:

  • 所以呃......“不返回任何内容”,你的意思是没有输出吗?因为bonk1.test() 肯定返回 一个值,但你需要print(bonk1.test()) 这样的事情
  • 是的。我没有想到这一点;我的假设是return 会像__str____repr__ 一样输出字符串。不过,你是对的。谢谢。 :)
  • __str____repr__ 不会自动打印任何内容。您可能会对 IDE 的某个功能感到困惑。

标签: python string if-statement


【解决方案1】:

您对如何编写 OOP 类有一点误解,尽管这是一个很好的尝试,因为您走在了正确的轨道上!

这是您想要实现的目标的有效实现:

class Bonk:
    def __init__(self, thing):
        self.thing = thing
  
    def test(self):
        if (self.thing == 'flarn'):
            return 'you have flarn'
        return 'you have nothing'

bonk1 = Bonk('glurm')
bonk2 = Bonk('flarn')

print(bonk1.test()) # you have nothing
print(bonk2.test()) # you have flarn

说明

在创建 Python 对象时,__init__ 是一个自定义函数,被调用以便为对象分配属性。

def __init__(self, thing): # Bonk object constructor with property
    self.thing = thing # Set the property for this object

然后您可以为每个对象创建额外的函数,例如test(),它将self 作为第一个参数,在调用时将引用对象本身。

def test(self):
    if (self.thing == 'flarn'): # Check the saved property of this object
        return 'you have flarn'
    return 'you have nothing'

相关文档: https://docs.python.org/3/tutorial/classes.html#class-objects

【讨论】:

  • ...所以我必须print() 吗? sigh 来自 JS/PHP 核心,Python 处理字符串的方式让我很头疼……我所做的是将returns 替换为prints 并添加了return True/False分别,但我完全理解(现在)为什么我必须print该方法(因为它是......)。 SMH。谢谢。
【解决方案2】:

离开 cmets 和其他建议的解决方案,您也可以这样做并通过在初始化程序中实现该函数检查来避免使用另一个函数 def test()。更少的代码行就可以完成工作。

class Bonk:
   def __init__(self, thing):
     self.thing = thing
     if self.thing == 'flarn':
       print('you have flarn')
     else:
       print('you have nothing')

bonk1 = Bonk('glurm')
bank2 = Bonk('flarn')

=== output ===
you have nothing
you have flarn

【讨论】:

  • 不。对不起。不要让方法名误导你;它仍然需要是一种方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
  • 1970-01-01
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
  • 2020-04-20
  • 2012-07-25
相关资源
最近更新 更多