1

I am trying to create a class which has a static method which returns list of its own instances. How can I do this without referring to the class name:

 1: class MyCar(object):
 2:  def __init__(self, number):
 3:    self._num = number
 4: 
 5:  @staticmethod
 6:  def get_cars_from(start=0, end=10):
 7:    """ This method get a list of cars from number 1 to 10.
 8:    """
 9:    return_list = []
10:    for i in range(start, end):
11:      instance = MyCar(i)
12:      return_list.append(instance)
13:    return return_list

This code works perfectly fine. But I have to reuse this code (copy+paste) in various classes, like Bus, Ship, Plane, Truck.

I am looking for a way to reuse above code in all these classes by making a generic way of instantiating instance of current class. Basically replace line #11 from:

  11: instance = MyCar(i)

to a more generic state which can be reused in any class. How can I do this ?

3
  • Yes, can't place them in base class, the example is a little different from the real implementation I'm working on. For now assume that I can't put this in base class. Commented Nov 23, 2015 at 14:55
  • It looks like you want to create a "Vehicle" class then make your classes Car, Bus, Plane etc inherit from it. There are very good tutorials on Google for inheritance in Python. Commented Nov 23, 2015 at 14:56
  • You could create a base class with that static method and then cast the result objects to your specific type Commented Nov 23, 2015 at 15:56

1 Answer 1

2

Use a class method, not a static method. That way, assuming for example that Bus inherits MyCar, then Bus.get_cars_from() will call the inherited MyCar.get_cars_from, but the cls argument will be set to Bus.

@classmethod
def get_cars_from(cls, start=0, end=10):
    """ This method get a list of cars from number 1 to 10.
    """
    return_list = []
    for i in range(start, end):
        instance = cls(i)
        return_list.append(instance)
    return return_list

Also, a list comprehension makes this a more-efficient one-liner:

@classmethod
def get_cars_from(cls, start=0, end=10):
    return [cls(i) for i in range(start, end)]

(but use xrange instead of range in Python 2).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.