Jhon
Jhon

Reputation: 145

Python use implicit argument instead of explicit

Haii, I'm new to python. I have this dummy code:

class Reader:

  def __init__(self, a_list):
    self.a_list = a_list

  def read(self):
    s = "The list reads as such:"
    for index, value in enumerate(self.a_list, start=1):
      s = s + "\n  element number {} is:  {}".format(index, value)
    print(s)

I want to know how can I use:

["haii", "my", "name", "is", "Jhon"].read()

instead of:

Reader(["haii", "my", "name", "is", "Jhon"]).read()

Upvotes: 1

Views: 226

Answers (2)

Abhishek J
Abhishek J

Reputation: 2584

Not exactly what you wanted [].read() won't work but list([]).read() will.

Also Note: This is highly unrecommended! Changing built in types can have terrible consequences. Your Reader wrapper was the best way to do it.

class MyList(list):
    def read(self):
        s = "The list reads as such:"
        for index, value in enumerate(self, start=1):
            s = s + "\n  element number {} is:  {}".format(index, value)
        print(s)


list = MyList
lst = list(["haii", "my", "name", "is", "Jhon"])
lst.read()

Upvotes: 2

Ali Hassan
Ali Hassan

Reputation: 966

you can not use this ["haii", "my", "name", "is", "Jhon"].read(). But you can use this read(["haii", "my", "name", "is", "Jhon"]) by adding an argument in read function.

class Reader:

  def read(self, list1):
    s = "The list reads as such:"
    for index, value in enumerate(list1, start=1):
      s = s + "\n  element number {} is:  {}".format(index, value)
    print(s)


Obj = Reader()

Obj.read(["haii", "my", "name", "is", "Jhon"])

Upvotes: 1

Related Questions