开发者

Casting in python

I have problem with casting in python.

I have a method in file module_A.py:

import Common.Models.Pax as Pax

def verify_passangers_data(self,paxes):
    for i in range(len(paxes)):
         pax=paxes[i]

Here is my Pax.py

class Pax:
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """C开发者_高级运维onstructor"""
    #----------------------------------------------------------------------



class Adult(Pax):

    def __init__(self,last_day_of_travel,first_name,last_name,nationality,address=None):
        self.birth_day=datetime.today() - timedelta(days = random.randrange(6563, 20793-(date.today()-last_day_of_travel).days))
        self.first_name=first_name
        self.last_name=last_name
        self.nationality=nationality
        self.address=address

This is how I create collection in another module(module_C.py):

paxes=[]
        paxes.append(Pax.Adult(last_day_of_travel,'FirstName','LastName',Nationality.Poland,DataRepository.addresses['Default']))

but, look at my output from debug probe (in wing ide)

>>> type(pax)
<class 'Common.Models.Pax.Adult'>
>>> pax is Common.Models.Pax.Adult
Traceback (most recent call last):
  File "<string>", line 1, in <fragment>
builtins.NameError: name 'Common' is not defined

How can I check is pax is instance of Adult?


How can I check is pax is instance of Adult?

Use the isinstance function:

isinstance(pax, Common.Models.Pax.Adult)

Make you have imported the class, though (e.g., import Common.Models.Pax).

(Although purists would argue that there's rarely a need to check the type of a Python object. Python is dynamically typed, so you should generally check to see if an object responds to a particular method call, rather than checking its type. But you may have a good reason for needing to check the type, too.)


You can use isinstance:

isinstance(pax, Common.Models.Pax.Adult)

Or the builtin type function:

type(pax) == Common.Models.Pax.Adult

Of course, you will have to import the module so that Common.Models.Pax.Adult is defined. That's why you're getting that error at the end.


You need to have imported the type in order to reference it:

>>> x is socket._fileobject
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'socket' is not defined
>>> import socket
>>> x is socket._fileobject
False

Presumably, you obtained the instance pointed to by pax from some other call, so you haven't actually imported the class into your namespace.

Also, is tests object identity (are these the same object?), not type. You want instanceof(pax,Common...).


You have two errors, first one is using is instead of isinstance function. Second is trying to refer module by it's absolute name, but you've imported it with alias.

Thus what you should do is:

isinstance(pax,Pax.Adult)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜