Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ตรวจสอบว่า type ใน argument แรกเป็น subclass ของ argument ที่สองใน Python


ภาพรวม

ใช้ numpy.issubsctype() ตรวจสอบว่า type ใน argument แรกเป็น subclass ของ argument ที่สอง ทั้งสอง argument เป็น datatypes

ขั้นตอนการทำงาน

1. นำเข้า NumPy

import numpy as np

2. ทดสอบ issubsctype() กรณีต่างๆ

print("Result...", np.issubsctype(np.float16, np.float32))
print("Result...", np.issubsctype(np.int32, np.signedinteger))
print("Result...", np.issubsctype('i4', np.signedinteger))
print("Result...", np.issubsctype('S8', str))
print("Result...", np.issubsctype(np.array([45, 89]), int))
print("Result...", np.issubsctype(np.array([5., 25., 40.]), float))

ตัวอย่างโค้ดเต็ม

import numpy as np
print("Using the issubsctype() method in Numpy\n")
print("Result...", np.issubsctype(np.float16, np.float32))
print("Result...", np.issubsctype(np.int32, np.signedinteger))
print("Result...", np.issubsctype('i4', np.signedinteger))
print("Result...", np.issubsctype('S8', str))
print("Result...", np.issubsctype(np.array([45, 89]), int))
print("Result...", np.issubsctype(np.array([5., 25., 40.]), float))

ผลลัพธ์

Using the issubsctype() method in Numpy
Result... False
Result... True
Result... True
Result... False
Result... True
Result... True

คำอธิบาย:

  • float16 ไม่ใช่ subclass ของ float32
  • int32 เป็น subclass ของ signedinteger
  • 'i4' (dtype string int32) เป็น subclass ของ signedinteger
  • 'S8' ไม่ใช่ subclass ของ str
  • np.array([45,89]) มี dtype int64 → เป็น subclass ของ int
  • np.array([5.,25.,40.]) มี dtype float64 → เป็น subclass ของ float

ความต่างกับ issubclass_: issubsctype ทำงานกับ dtype objects โดยตรง ส่วน issubclass_ ทำงานกับ class objects