Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Unexpected expected type error result
# creating a new kind of class or instance attribute

class Integer:
    def __init__(self, name): = name

    def __get__(self, instance, cls):
        if instance is None:
            return self
            return instance.__dict__[]

    def __set__(self, instance, value):
        if not isinstance(value, int):
            raise TypeError('expected an int')
        instance.__dict__[] = value

    def __delete__(self, instance):
        del instance.__dict__[self]

class Point:
    x = Integer('x')
    y = Integer('y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(12, 3)
my_int = Integer(1)
print('myint:   {}   {}'.format(my_int,
print('{}   {}'.format(p.x, p.y))

my_int2 = Integer('1')
print('myint2:  {}   {}'.format(my_int2,
# p2 = Point('1', 3)
my_int2 = Integer('1')
does not produce the expected type error
while uncommenting p2 does raise the expected error
TypeError: expected an int
I wasn't familiar before with these magic methods but here's what I learned...

You've constructed Integer such that in Point, when self.x and self.y are assigned (or "__set__"), that the TypeError-raising code gets called. Merely constructing an integer directly only invokes its initializer, not its __set__ method. So this code appears to be working as it ought to. (I'm not as sure about __get__ or __delete__, but that's not what your question seems to be about.)

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Type Error: bad operand type for unary +: 'str' Psypher1 2 80 Aug-12-2019, 02:30 PM
Last Post: Psypher1
  catch input type error mcmxl22 5 135 Aug-11-2019, 07:33 AM
Last Post: wavic
  Type error: dump() missing 1 required positional argument: fp jaycuff13 2 419 Jul-13-2019, 10:21 AM
Last Post: jaycuff13
  Unexpected Output using classes and inheritance langley 2 145 Jul-04-2019, 09:33 AM
Last Post: langley
  ImportError has not raised in pkg_resources module but expected tamilselvanvjm 2 167 Jun-19-2019, 10:06 AM
Last Post: tamilselvanvjm
  remove tags from BeautifulSoup result moski 1 184 Jun-05-2019, 01:47 PM
Last Post: heiner55
  call dict object result key error lateublegende 2 231 May-15-2019, 01:08 PM
Last Post: lateublegende
  Type error when reading in different data types on an __init__ method Dylanmull 3 223 May-09-2019, 02:05 PM
Last Post: buran
  syntax error near unexpected token btom529 5 500 Apr-21-2019, 09:03 PM
Last Post: btom529
  Getting error "Type error-a bytes-like object..." mrapple2020 1 353 Apr-06-2019, 06:37 PM
Last Post: mrapple2020

Forum Jump:

Users browsing this thread: 1 Guest(s)