1 | n/a | from ctypes import * |
---|
2 | n/a | import unittest |
---|
3 | n/a | |
---|
4 | n/a | class X(Structure): |
---|
5 | n/a | _fields_ = [("a", c_int), |
---|
6 | n/a | ("b", c_int)] |
---|
7 | n/a | new_was_called = False |
---|
8 | n/a | |
---|
9 | n/a | def __new__(cls): |
---|
10 | n/a | result = super().__new__(cls) |
---|
11 | n/a | result.new_was_called = True |
---|
12 | n/a | return result |
---|
13 | n/a | |
---|
14 | n/a | def __init__(self): |
---|
15 | n/a | self.a = 9 |
---|
16 | n/a | self.b = 12 |
---|
17 | n/a | |
---|
18 | n/a | class Y(Structure): |
---|
19 | n/a | _fields_ = [("x", X)] |
---|
20 | n/a | |
---|
21 | n/a | |
---|
22 | n/a | class InitTest(unittest.TestCase): |
---|
23 | n/a | def test_get(self): |
---|
24 | n/a | # make sure the only accessing a nested structure |
---|
25 | n/a | # doesn't call the structure's __new__ and __init__ |
---|
26 | n/a | y = Y() |
---|
27 | n/a | self.assertEqual((y.x.a, y.x.b), (0, 0)) |
---|
28 | n/a | self.assertEqual(y.x.new_was_called, False) |
---|
29 | n/a | |
---|
30 | n/a | # But explicitly creating an X structure calls __new__ and __init__, of course. |
---|
31 | n/a | x = X() |
---|
32 | n/a | self.assertEqual((x.a, x.b), (9, 12)) |
---|
33 | n/a | self.assertEqual(x.new_was_called, True) |
---|
34 | n/a | |
---|
35 | n/a | y.x = x |
---|
36 | n/a | self.assertEqual((y.x.a, y.x.b), (9, 12)) |
---|
37 | n/a | self.assertEqual(y.x.new_was_called, False) |
---|
38 | n/a | |
---|
39 | n/a | if __name__ == "__main__": |
---|
40 | n/a | unittest.main() |
---|