Skip to content

Commit c00de80

Browse files
committed
Don't inherit __init__ from base class
1 parent 3154dc3 commit c00de80

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

include/pybind11/class_support.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,9 @@ inline PyObject* make_new_python_type(const type_record &rec) {
428428
if (bases.size() > 0)
429429
type->tp_bases = bases.release().ptr();
430430

431+
/* Don't inherit base __init__ */
432+
type->tp_init = pybind11_init;
433+
431434
/* Supported protocols */
432435
type->tp_as_number = &heap_type->as_number;
433436
type->tp_as_sequence = &heap_type->as_sequence;

tests/test_inheritance.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ class Hamster : public Pet {
3636
Hamster(const std::string &name) : Pet(name, "rodent") {}
3737
};
3838

39+
class Chimera : public Pet {
40+
Chimera() : Pet("Kimmy", "chimera") {}
41+
};
42+
3943
std::string pet_name_species(const Pet &pet) {
4044
return pet.name() + " is a " + pet.species();
4145
}
@@ -74,6 +78,8 @@ test_initializer inheritance([](py::module &m) {
7478
py::class_<Hamster, Pet>(m, "Hamster")
7579
.def(py::init<std::string>());
7680

81+
py::class_<Chimera, Pet>(m, "Chimera");
82+
7783
m.def("pet_name_species", pet_name_species);
7884
m.def("dog_bark", dog_bark);
7985

tests/test_inheritance.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33

44
def test_inheritance(msg):
5-
from pybind11_tests import Pet, Dog, Rabbit, Hamster, dog_bark, pet_name_species
5+
from pybind11_tests import Pet, Dog, Rabbit, Hamster, Chimera, dog_bark, pet_name_species
66

77
roger = Rabbit('Rabbit')
88
assert roger.name() + " is a " + roger.species() == "Rabbit is a parrot"
@@ -30,6 +30,10 @@ def test_inheritance(msg):
3030
Invoked with: <m.Pet object at 0>
3131
"""
3232

33+
with pytest.raises(TypeError) as excinfo:
34+
Chimera("lion", "goat")
35+
assert "No constructor defined!" in str(excinfo.value)
36+
3337

3438
def test_automatic_upcasting():
3539
from pybind11_tests import return_class_1, return_class_2, return_class_n, return_none

0 commit comments

Comments
 (0)