1

Let's say that I want to create a class, apply a method and set an attribute to the resulted object.

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

class Transformer:

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

    def operator(self):
        operator = (self.array * 2) + 60
        return operator

    @staticmethod
    def meta(array):
        meta = (max(array) + 17)
        return meta

    def to_operator(self):
        op = self.operator()
        meta = self.meta(op)
        setattr(op, 'meta', meta)# or op.meta = meta
        return op


t = Transformer(np.array([1, 2, 3]))
t1 = t.to_operator()
print(t1.meta())

here I get the following error:

AttributeError: 'numpy.ndarray' object has no attribute 'meta'

expected result:

 >>> 83
mallet
  • 2,454
  • 3
  • 37
  • 64
  • How about replacing the *staticmethod* by a *classmethod* ? – ma3oun Jul 17 '19 at 12:59
  • 1
    Next time add the full error traceback to your question, because there you can find the cause of your error. I added an answer with more info. – Ralf Jul 17 '19 at 13:04

1 Answers1

0

When running your code, I get the error and it shows the offending line as setattr(op, 'meta', meta):

Traceback (most recent call last):
  File "/home/ralf/PycharmProjects/scratch_pad/run.py", line 44, in <module>
    t1 = t.to_operator()
  File "/home/ralf/PycharmProjects/scratch_pad/run.py", line 29, in to_operator
    setattr(op, 'meta', meta)
AttributeError: 'numpy.ndarray' object has no attribute 'meta'

Read about the cause in these related questions:

Ralf
  • 16,086
  • 4
  • 44
  • 68