isosceleswheel
isosceleswheel

Reputation: 1546

Set the return value for a Python class instance when it is called by name

I have a Python class with the attribute _mylist. I want instances of MyClass to return _mylist when I call them by name. Here is the basic idea of what I want to define followed by example input and output.

class MyClass:
    def __init__(self, a, b):
        self._mylist = [a, b]

    def _returnlist(self):
        # method conferring MyClass with the property that calls to class
        # instances returns self._mylist 
        pass


>>> mc = MyClass(a, b)
>>> mc  # the desired property: call to mc returns mc._mylist
[a, b]
>>> k = mc  # assignment from mc instance only assigns mc._mylist
>>> k
[a, b]

Is there a standard way to give a class this property?

Upvotes: 0

Views: 52

Answers (1)

jwodder
jwodder

Reputation: 57470

This cannot be done. Unlike, say, C++, Python does not give you a way to overload the meaning of k = mc so that k is instead set to mc._mylist. In Python, k = mc will always set k to mc.

Upvotes: 2

Related Questions