object.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include "test.h"
  2. namespace {
  3. const char* source = R"(
  4. class Point:
  5. def __init__(self, x, y):
  6. self.x = x
  7. self.y = y
  8. def __add__(self, other):
  9. return Point(self.x + other.x, self.y + other.y)
  10. def __sub__(self, other):
  11. return Point(self.x - other.x, self.y - other.y)
  12. def __mul__(self, other):
  13. return Point(self.x * other.x, self.y * other.y)
  14. def __truediv__(self, other):
  15. return Point(self.x / other.x, self.y / other.y)
  16. def __floordiv__(self, other):
  17. return Point(self.x // other.x, self.y // other.y)
  18. def __mod__(self, other):
  19. return Point(self.x % other.x, self.y % other.y)
  20. def __pow__(self, other):
  21. return Point(self.x ** other.x, self.y ** other.y)
  22. def __lshift__(self, other):
  23. return Point(self.x << other.x, self.y << other.y)
  24. def __rshift__(self, other):
  25. return Point(self.x >> other.x, self.y >> other.y)
  26. def __eq__(self, other):
  27. return self.x == other.x and self.y == other.y
  28. def __ne__(self, other) -> bool:
  29. return not self.__eq__(other)
  30. def __lt__(self, other) -> bool:
  31. return self.x < other.x and self.y < other.y
  32. def __le__(self, other) -> bool:
  33. return self.x <= other.x and self.y <= other.y
  34. def __gt__(self, other) -> bool:
  35. return self.x > other.x and self.y > other.y
  36. def __ge__(self, other) -> bool:
  37. return self.x >= other.x and self.y >= other.y
  38. def __repr__(self):
  39. return f'Point({self.x}, {self.y})'
  40. )";
  41. TEST_F(PYBIND11_TEST, object) {
  42. py::module m = py::module::import("__main__");
  43. py::exec(source);
  44. py::exec("p = Point(3, 4)");
  45. py::object p = py::eval("p");
  46. // is
  47. EXPECT_FALSE(p.is_none());
  48. EXPECT_TRUE(p.is(p));
  49. // attrs
  50. EXPECT_EQ(p.attr("x").cast<int>(), 3);
  51. EXPECT_EQ(p.attr("y").cast<int>(), 4);
  52. p.attr("x") = py::int_(5);
  53. p.attr("y") = py::int_(6);
  54. EXPECT_EQ(p.attr("x").cast<int>(), 5);
  55. EXPECT_EQ(p.attr("y").cast<int>(), 6);
  56. EXPECT_EXEC_EQ("p", "Point(5, 6)");
  57. // operators
  58. EXPECT_EVAL_EQ("Point(10, 12)", p + p);
  59. EXPECT_EVAL_EQ("Point(0, 0)", p - p);
  60. EXPECT_EVAL_EQ("Point(25, 36)", p * p);
  61. EXPECT_EVAL_EQ("Point(1, 1)", p / p);
  62. // EXPECT_EVAL_EQ("Point(0, 0)", p // p);
  63. EXPECT_EVAL_EQ("Point(0, 0)", p % p);
  64. // iterators
  65. py::object l = py::eval("[1, 2, 3]");
  66. int index = 0;
  67. for(auto item: l) {
  68. EXPECT_EQ(item.cast<int>(), index + 1);
  69. index++;
  70. }
  71. }
  72. } // namespace