Home > Software engineering >  Variable inside an expression in python
Variable inside an expression in python

Time:09-19

EDIT: I am editing the whole question in order to be more clear, and to change something that was wrong in the previous example.

Since I am really not sure how to explain the question, I will use the following example.

Let's say I have some classes that are called apple, banana and orange. I would like to create a function, that will take as an input one of these classes. Each class has a function that is called eating() that is what I want to call with the following function:

def function(banana):
    a = banana.eating()
    return a 

The point is: if I put as an input the class apple, I would like a to take the value of apple.eating(). Hence, the name of the input variable should go in the expression somehow.

To be a bit more specific, the classes would be:

class apple:
    def __init__:
         blahblah
    def eating(self):
         blahblah

class banana:
     def __init__:
          blahblah
     def eating(self):
          blahblah

CodePudding user response:

You don't have to do anything. Your code

def func(name):
    fruit = name.function()
    return fruit

will work al long as the argument you supply it is an object that has a function method.

Keep in mind that in Python "variables" are nothing more than labels that refer objects.

CodePudding user response:

You can inherit from a fruit metaclass

class fruit:
    def cfunc(self):
        print("Class: "   str(self.__class__))

class apple(fruit):
    def __init__(self):
        pass

class banana(fruit):
    def __init__(self):
        pass

banana().func()
apple().func()

# Output:
# Class: <class '__main__.banana'>
# Class: <class '__main__.apple'>


def func(obj):
    return obj.cfunc()

func(banana())

# Output:
# Class: <class '__main__.banana'>
  • Related