Testing variable types in Python

I create an initialization function for the Room class and find that the program will not accept the tests that I did on the input variables.

Why is this?

def __init__(self, code, name, type, size, description, objects, exits):
    self.code = code
    self.name = name
    self.type = type
    self.size = size
    self.description = description
    self.objects = objects
    self.exits = exits
            #Check for input errors:
    if type(self.code) != type(str()):
        print 'Error found in module rooms.py!'
        print 'Error number: 110'
    elif type(self.name) != type(str()):
        print 'Error found in module rooms.py!'
        print 'Error number: 111'
    elif type(self.type) != type(str()):
        print 'Error found in module rooms.py!'
        print 'Error number: 112'
    elif type(self.size) != type(int()):
        print 'Error found in module rooms.py!'
        print 'Error number: 113'
    elif type(self.description) != type(str()):
        print 'Error found in module rooms.py!'
        print 'Error number: 114'
    elif type(self.objects) != type(list()):
        print 'Error found in module rooms.py!'
        print 'Error number: 115'
    elif type(self.exits) != type(tuple()):
        print 'Error found in module rooms.py!'
        print 'Error number: 116'

When I run this, I get this error:

Traceback (most recent call last):
  File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa   I/rooms.py", line 148, in <module>
    myRoom = Room(101, 'myRoom', 'Basic Room', 5, '<insert description>', myObjects, myExits)
  File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/rooms.py", line 29, in __init__
    if type(self.code) != type(str()):
TypeError: 'str' object is not callable

---- Thanks for the help, but: -----

Is this applicable to isinstance (item, list) or isinstance (item, tuple)?

+3
source share
7 answers

Not answering why, but

  • stritself is already a type. you can usetype(self.code) != str
  • But better to use isinstance(self.code, str).
+9
source

Python - . . , , , .

C/++/Java, , .

+8

:

  • "type". "", . , , "type" .

  • ? , .

, - python. .

+3

, .

.

, Cython Pyrex, . , C- Python.

+1

, , , assert, stdout.

assert isinstance(code, str)
assert isinstance(name, str)
...
+1

. , , :

if isinstance(item, str):
   # do your thing
0

python , , . - , , try/catch.

def addOne(a):
    ''' 
    increments a with 1 if a is a number. 
    if a is a string, append '.' to it.    
    '''
    try:
        return a + 1
    except TypeError:
        return a + "."

.

-1

Source: https://habr.com/ru/post/1737787/


All Articles