user2766739
user2766739

Reputation: 477

Python - call a method from a class just as you are instantiating it?

Is it possible to call a method from the class just as you are instantiating it?

I tried the following but kept getting

Base Class:
    class A(object):
    """ Parent class """
    def __init__(self, **kwargs):     

        # query parameters
        self.start_time     = kwargs.get('start_time', None)


    def set_query_starttime(self, str_time):
        """ sets query start time """
        if self.verbosity:
            print("I: Set query start time parameter")

        if not str_time:
            return

        utc_start_time = self._format_time(str_time)

        try:
            self.query.SetStartTime(utc_start_time.tm_year,
                                    utc_start_time.tm_mon,
                                    utc_start_time.tm_mday,
                                    utc_start_time.tm_hour,
                                    utc_start_time.tm_min,
                                    utc_start_time.tm_sec)

        except pythoncom.com_error as error:
            e = format_com_message("Failed to format date")
            raise Error(e)

I want to instantiate the base Class and call the set_query_starttime method just as I'm instantiating the class:

myStartTime = "Sun Nov 03 20:00:00 2013"
myEndTime = "Sun Nov 03 21:00:00 2013"

test = A(start_time = A.set_query_starttime(myStartTime))

But kept getting: TypeError: unbound method set_query_starttime() must be called with A instance as first argument (got str instead)

I even tried adding @staticmethod to the base class' set_query_starttime function but still get same error.

Upvotes: 2

Views: 7472

Answers (2)

tdelaney
tdelaney

Reputation: 77347

Just pass in the string on class instantiation and call the method in __init__.

class A(object):
""" Parent class """
def __init__(self, start_time=None):     
    if start_time:
        self.set_query_starttime(start_time)

...etc...

then use it as:

myStartTime = "Sun Nov 03 20:00:00 2013"
myEndTime = "Sun Nov 03 21:00:00 2013"

test = A(start_time=myStartTime)

Upvotes: 2

TerryA
TerryA

Reputation: 59974

This is because you're trying to call a function in a class without first making an instance. This method is then unbound.

To fix this, you can do A().set_query_starttime which will call the function with an instance.

temp = A().set_query_starttime(myStartTime)
test = A(start_time=temp)

Upvotes: 1

Related Questions