ctypes结构中的默认值 [英] Default values in a ctypes Structure
本文介绍了ctypes结构中的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在ctypes结构中,可以指定默认值吗?
In a ctypes Structure, is it possible to specify default values?
例如,使用常规的python函数,您可以执行以下操作:
For example, with a regular python function, you can do this:
def func(a, b=2):
print a + b
这将允许这种行为:
func(1) # prints 3
func(1, 20) # prints 21
func(1, b=50) # prints 51
是否可以在ctypes结构中执行此操作?
Is it possible to do this in a ctypes Structure?
例如:
class Struct(Structure):
_fields_ = [("a", c_int), ("b", c_int)] # b default should be 2
def print_values(self):
print self.a, self.b
struct_instance = Struct(1)
struct_instance.print_values() # should somehow print 1, 2
推荐答案
是.只需覆盖 __init__
方法.
Yes. Simply override the __init__
method.
class Struct(Structure):
_fields_ = [("a", c_int), ("b", c_int)]
def __init__(self, a, b=2):
super(Struct, self).__init__(a, b)
def print_values(self):
print(self.a, self.b)
这篇关于ctypes结构中的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文