← 输入框|github.com|刷新
Skip to content

Constructor executed twice when overriding constructor in System.Object. #495

Closed

Description

@klasma

Environment

  • Pythonnet version: 2.3.0
  • Python version: 2.7.13
  • Operating System: Windows 10

Details

We are trying to create a subclass of System.Object (using namespace) and override the constructor.

For some reason, the conctructor is executed twice when an instance of the class is created. Below is an example that reproduces the problem.

class X(System.Object):
    __namespace__ = "PyTest"

    def __init__(self):
        print("Running X constructor")

x = X()

The output is

Running X constructor
Running X constructor

Activity

  1. rickardraysearch commented on Jun 15, 2017

    @rickardraysearch
    Contributor

    Furthermore, if you add arguments to the constructor, the arguments are only passed the second time.

    class X(System.Object):
        __namespace__ = "PyTest"
    
        def __init__(self, *args):
            print("Running X constructor, args = {0}".format(args))
    
    x = X(1,2)

    produces the output

    Running X constructor, args = ()
    Running X constructor, args = (1, 2)
    

    It seems that the first invocation is from the call in Python.Runtime.MetaType.tp_call to tp_new, whereas the second invocation is from the call to py__init__ using Runtime.PyObject_Call.

    Is the error that somehow the call to tp_new also ends up calling __init__?

  2. filmor commented on Jun 16, 2017

    @filmor
    Member

    Hmm, the comment says

        /// Metatype __call__ implementation. This is needed to ensure correct
        /// initialization (__init__ support), because the tp_call we inherit
        /// from PyType_Type won't call __init__ for metatypes it doesn't know.
    

    Maybe this changed in Python? I'll have a look.

  3. added a commit that references this issue on Jun 26, 2017
  4. filmor commented on Jul 11, 2017

    @filmor
    Member

    Fixed by #503.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions