0

I'm new to python so I don't know much. I was defining a function to work with lists and I want that function to be used like an attribute. For example to sort a list we use: list.sort()

Basically, instead of using the function like function(list) I want to use it like this: list.function()

1
  • For that you can define a class while inherit the inbuilt list class (so that you will be able use all the existing list methods) with methods as additional desired function/behavior. Commented Jan 19, 2023 at 17:12

3 Answers 3

1

You have to create a class

class MyClass():
    def function(self, param):
        print(param)

myClass = MYClass()
myClass.function()

You can see here or here for more details

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

Comments

1

You'll have to make a class that inherits the list class.

class MyList(list):
    def __init__(self, *args):
        super().__init__(*args)
        
    def all_caps(self):
        return [item.upper() if isinstance(item, str) else item for item in self]
    
mylist = MyList(['hi', 'hello', 1234])

mylist.all_caps()

3 Comments

But I'd have to convert the list to a MyList data type in order to use this, is there any way to just use a list directly?
Not that I'm aware of. Is there a particular reason you want this behavior?
I'm making a function which will work with lists, and I want it to be used like the sort function in which we attribute listname in front of function.
0

You will have to create a custom class that inherit from original list and then using builtins module assign new extended class to previous list:

import builtins

class my_list(list):
  def f(self):
    return sum(self)

builtins.list = my_list


arr = list([1,2,3])
x = arr.f()
print(x)

Output:

6

Warning

Remember that you need to create every list using list() function to make sure your method will work.

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.