Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values in a ctypes Structure

In a ctypes Structure, is it possible to specify default values?

For example, with a regular python function, you can do this:

def func(a, b=2):
    print a + b

That would allow for this behaviour:

func(1) # prints 3

func(1, 20) # prints 21

func(1, b=50) # prints 51

Is it possible to do this in a ctypes Structure?

for example:

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
like image 574
Lewis Ellis Avatar asked Oct 30 '11 17:10

Lewis Ellis


1 Answers

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)
like image 200
Petr Viktorin Avatar answered Sep 18 '22 15:09

Petr Viktorin