Home > Enterprise >  Python - Class object as function argument: Object only - Class not in argument
Python - Class object as function argument: Object only - Class not in argument

Time:10-25

I am trying to write a function taking a string as an argument and using this argument as a class object.

Note that my explanantion might be strangely formulated sice I could not find an answer online. The MWE below should clarify what I mean, the problematic line is indicated.

Edit: in the MWE, "print" is an example. I need to be able to call the object to update it, print it or, in the case of a list, append to it. I need access to the object itself, not the value of the object.

MWE

# Create a class
class myClass():
    def __init__(self):
        self.one = "Test"
        self.two = "Plop"

# Define function
def myFunction (parameter):
    print(myObject.parameter)##### This line is currently not possible.

# Use class
myObject = myClass()

# Use function
myFunction("one")

I am not trying to append a new object to the class, only to call an existing object.

Is this even possible?

CodePudding user response:

Looks like you need the built-in function called getattr

my_object = myClass()

def my_function(parameter):
    print(getattr(my_object, parameter, None))

also this is not the best practice to call objects from outer scope like that. i'd suggest to add it as your class method:

class MyClass():
    def __init__(self):
        self.one = "Test"
        self.two = "Plop"

    def get(self, parameter):
        return getattr(self, parameter, None)

and then just call it w/ MyClass().get("one")

CodePudding user response:

You need to use getarttr():

# Create a class
class myClass():
    def __init__(self):
        self.one = "Test"
        self.two = "Plop"




# Use class
myObject = myClass()

# Define function
def myFunction(parameter):
    print(getattr(myObject, parameter))##### This line is currently possible.


# Use function
myFunction("one")
  • Related