Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Constructor (object-oriented programming)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Python === In [[Python (programming language)|Python]], constructors are defined by one or both of <code>__new__</code> and <code>__init__</code> methods. A new instance is created by calling the class as if it were a function, which calls the <code>__new__</code> and <code>__init__</code> methods. If a constructor method is not defined in the class, the next one found in the class's Method Resolution Order will be called.<ref name="auto">{{Cite web|url=https://docs.python.org/3/reference/datamodel.html|title=3. Data model|website=Python documentation}}</ref> In the typical case, only the <code>__init__</code> method need be defined. (The most common exception is for immutable objects.) <syntaxhighlight lang="pycon"> >>> class ExampleClass: ... def __new__(cls, value): ... print("Creating new instance...") ... # Call the superclass constructor to create the instance. ... instance = super(ExampleClass, cls).__new__(cls) ... return instance ... def __init__(self, value): ... print("Initialising instance...") ... self.payload = value >>> exampleInstance = ExampleClass(42) Creating new instance... Initialising instance... >>> print(exampleInstance.payload) 42 </syntaxhighlight> Classes normally act as [[Factory (object-oriented programming)|factories]] for new instances of themselves, that is, a class is a callable object (like a function), with the call being the constructor, and calling the class returns an instance of that class. However the <code>__new__</code> method is permitted to return something other than an instance of the class for specialised purposes. In that case, the <code>__init__</code> is not invoked.<ref name="auto"/>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)