Home > Software design >  Making custom Attributes in Python
Making custom Attributes in Python

Time:01-22

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()

CodePudding user response:

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

CodePudding user response:

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()

CodePudding user response:

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.

  • Related