简体   繁体   中英

How to make a Class return an object when the class is referenced after it has been initialized?

How to make a class return an object in the following way:

import numpy as np

a = np.array([(1,2),(3,4)])

Whenever a is referenced, it returns

array([[1, 2],
       [3, 4]])

However when I create a simple class:

class Example:
    def __init__(self, data):
        self.nparray = np.array(data)

And run b = Example([(1,2),(3,4)]) then reference b I get: <__main__.Example at 0x7f17381099e8> . To return the value I need to run b.nparray .

How to make the class Example return

array([[1, 2],
       [3, 4]])

when b is referenced?

I tried using methods such as __new__ , __repr__ and __getitem__ however none produced the desired behavior.

Using Python's "magic methods", like the __init__ you've already seen, we can make the class execute code when certain things happen. One of these is __call__ , which executes when the class is called like a function.

Knowing this, you could use this code:

import numpy as np

class Example:
    def __init__(self, data):
        self.nparray = np.array(data)

    def __call__(self):
        # This function is called when an instance of Example is called
        return self.nparray

The result of this:

>>> b = Example([[1, 2], [3, 4]])
>>> b()
array([[1, 2],
       [3, 4]])

For more on magic methods, see this useful article .

You should use __repr__ in the following way:

class Example:
    def __init__(self, data):
            self.nparray = np.array(data)
    def __repr__(self):
            return repr(self.nparray)

This returns the representation the self.nparray object within:

>>> c = Example([(1, 2), (3, 4)])
>>> c
array([[1, 2],
       [3, 4]])

Of course this is used and during interactive sessions where you simply enter the name and press enter and if you print it with print(c) . If you need to limit to only for print calls you define __str__ for the object in question.

You can't return any data from a class init function. Have you tried something like:

class Example(object):
    nparray = None
    def __init__(self, data):
        self.nparray = np.array(data)
        return

    def getArray(self):
        return(self.nparray)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM