MarreMachine
MarreMachine

Reputation: 15

Class function return different results

I have 2 different ways to set up a python class. One that automaticly runs the class function, and one that you need to run manually.

Manually running function:

class testclass:
   def __init__(self, value):
      self.value = value

   def validator(self):
      data = self.value[0] + self.value[1]
      data = int(data)
      return data
theClass = testclass('123456')
print(theClass.validator())

This prints "12"

Automaticly running the function:

class testclass:
   def __init__(self, value):
      self.value = value
      self.validator()

   def validator(self):
      data = self.value[0] + self.value[1]
      data = int(data)
      return data
theClass = testclass('123456')
print(theClass)

this prints "<main.testclass object at 0x011C72B0>"

How can i run the class function automaticly, and still get 12 as print output?

Upvotes: 0

Views: 122

Answers (4)

Code Pope
Code Pope

Reputation: 5459

In the second version you are calling the validator function in __init__, but not returning the value that validator is returning. The problem is that __init__ is not able to return anything but None. What you can do is to assign the value to an instance variable:

class testclass:
  value = 0
  def __init__(self, value):
      self.value = value
      self.value = self.validator()

  def validator(self):
      data = self.value[0] + self.value[1]
      data = int(data)
      return data
theClass = testclass('123456')
print(theClass.value)

Ouptut:

12

Upvotes: 1

RetardedHorse
RetardedHorse

Reputation: 158

In your automatic example, you are not calling 'theClass'. Any function calls need (). You can rename your automatic validator the __call__ and call it as theClass().

See more at https://www.journaldev.com/22761/python-callable-call

Upvotes: 1

user2390182
user2390182

Reputation: 73480

Print inside the validator function:

class TestClass:  # sticking to more Pythonic naming conventions
    def __init__(self, value):
        self.value = value
        self.validator()

    def validator(self):
        print(int(self.value[0] + self.value[1]))

This will automatically print validation output whenever an instance is created:

>>> the_class = TestClass('123456')
12

Upvotes: 0

Peter
Peter

Reputation: 3495

If you simply want to print the output value, and not use it as a variable, you can define __str__ as part of your class.

class testclass(object):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return self.validator()

    def validator(self):
        data = self.value[0] + self.value[1]
        data = int(data)
        return data

>>> theClass = testclass('123456')
>>> print(theClass)
12

If you want to use it as a variable, such as theClass + 5, then using a custom class is not the way to go in this case.

Upvotes: 0

Related Questions