New Coder
New Coder

Reputation: 11

Define condition to Class

I am trying to define condition to class, if my object Does not meet the conditions:

The conditions: all the organs is vectors, the shape of the vectors is the same.

When I try to casting the object the function will return None.

Thats what I tried so far:

class Matrix:
    def __init__(self,m1):
        dic_len = {}
        self.m1 = tuple(m1)
        checking = 0
        for i in self.m1:
            dic_len[len(i)] = 'check'
            if type(i) != Vector:
                self.m1 = None
                checking = 1
        if len(dic_len) != 1:
            self.m1 = None
        if len(dic_len) == 1 and checking == 0:
            self.content = self.m1 = tuple(m1)
            self.shape = (len(m1),len(m1[0]))

    def __repr__(self):
        if self.m1 != None:
            return "(" + ", ".join(str(i) for i in self.m1) + ")"
        else:
            return None

But I get this error:

>>>v1 = Vector([1,2])
>>>v2 = Vector([4,5,6])
>>>m = Matrix([v1,v2])
>>>print(m)
TypeError: __str__ returned non-string (type NoneType)

i wish the function will return None.

Upvotes: 1

Views: 41

Answers (2)

snakecharmerb
snakecharmerb

Reputation: 55630

The CPython docs state for the __repr__ method state that

The return value must be a string object.

So returning None isn't going to work.

>>> class C:
...     def __repr__(self):
...         return None
... 

>>> c = C()
>>> repr(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __repr__ returned non-string (type NoneType)

If you're going to share your code with others, it might be better to code __repr__ to produce its coventional output:

...this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment)...

And override __str__ to produce a representation that indicates the validity of the object instance (though note __str__ must also return a string).

Upvotes: 1

YuhaoQI
YuhaoQI

Reputation: 69

return str(None)

instead of

return None

Upvotes: 2

Related Questions