简体   繁体   中英

Python: checking to see if a value is a certain object

I know if the isinstance() method, which can be used to check if a value is a certain type. For instance,

num = 3
print isinstance(num, int)

Gives us True .

I have a custom made object now, called Project . Project has some attributes that are specific. One of my methods uses a Project as a parameter, and I want to validate that the input parameter is indeed of type Project . Will the same method work?

是的,即使Project是自定义类, isinstance(obj, Project)是查看obj是否为Project实例的正确方法。

Yes.

class A:
    pass

print(isinstance(A(), A))

prints "True".

The function works well.

class A:
    #some code

X=A()
if(isinstance(X, A)):
    print "hello"

prints hello

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM