2011-10-30 22 views
7

W strukturze ctypes, czy możliwe jest określenie wartości domyślnych?Wartości domyślne w ctypes Struktura

Na przykład, z regularnym funkcji Pythona, można to zrobić:

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

Pozwoliłoby tego zachowania:

func(1) # prints 3 

func(1, 20) # prints 21 

func(1, b=50) # prints 51 

Czy to możliwe, aby to zrobić w strukturze ctypes?

na przykład:

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 

Odpowiedz

7

Tak. Wystarczy zastąpić metodę __init__.

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) 
+0

Dzięki! Nie wiem, dlaczego o tym nie myślałem. :) –

3

Jest wygodniejszy sposób, jeśli masz wiele struktur z wartościami domyślnymi różniącymi się od tych ctypes. Rozwiń ctypes.Structure na inną zmienną klasy _defaults_.

class BaseStructure(ctypes.Structure): 

    def __init__(self, **kwargs): 
     """ 
     Ctypes.Structure with integrated default values. 

     :param kwargs: values different to defaults 
     :type kwargs: dict 
     """ 

     values = type(self)._defaults_.copy() 
     for (key, val) in kwargs.items(): 
      values[key] = val 

     super().__init__(**values)   # Python 3 syntax 



class YourStructure(BaseStructure): 
    _fields_ = [ ("param1", ctypes.c_uint32), 
       ("param2", ctypes.c_uint32), 
       ("param3", ctypes.c_int32), 
       ] 
    _defaults_ = { "param1" : 42, 
        "param3" : -23, 
       } 
+0

Mówisz "Składnia Pythona 3" - jaki byłby odpowiednik w Pythonie 2.7? – slhck

+0

W Pythonie 2 musisz powtórzyć: '' 'super (YourStructure, self) .__ init __ (** values)' '' (http://stackoverflow.com/a/576183/2053808). – Chickenmarkus

Powiązane problemy