Home > Software design >  Python: string test not evaluating
Python: string test not evaluating

Time:11-25

I'm trying to do what should be simple string comparison, but I can't get it to work:

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()

This returns nothing. I've tried this too:

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

and that doesn't work either.

I've tried double quotes, assigning 'flarn' to a variable and then testing against the variable, adding a comma at the end of the list test. I tried passing it in as a variable instead... but nothing is working.

What am I missing?

CodePudding user response:

You have mistaken how to write OOP classes slightly, though a good attempt since you are on the right track!

Here is a working implementation of what you're trying to achieve:

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

Explanation

When creating a Python Object, the __init__ is a customization function that is called in order to assign properties to the object.

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

You can then create additional functions for each object, such as test(), which takes self as the first parameter that will reference the object itself when invoked.

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

Relevant Documentation: https://docs.python.org/3/tutorial/classes.html#class-objects

CodePudding user response:

Going off the comments and the other suggested solution, you can also do this and avoid the use of another function def test() by just implementing that function check within the initializer. Lesser lines of code and it does the job.

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
  • Related