Python constructors and __init__

前端 未结 5 452
耶瑟儿~
耶瑟儿~ 2020-11-30 18:57

Why are constructors indeed called "Constructors"? What is their purpose and how are they different from methods in a class?

Also, can there be more that on

5条回答
  •  独厮守ぢ
    2020-11-30 19:42

    Classes are simply blueprints to create objects from. The constructor is some code that are run every time you create an object. Therefor it does'nt make sense to have two constructors. What happens is that the second over write the first.

    What you typically use them for is create variables for that object like this:

    >>> class testing:
    ...     def __init__(self, init_value):
    ...         self.some_value = init_value
    

    So what you could do then is to create an object from this class like this:

    >>> testobject = testing(5)
    

    The testobject will then have an object called some_value that in this sample will be 5.

    >>> testobject.some_value
    5
    

    But you don't need to set a value for each object like i did in my sample. You can also do like this:

    >>> class testing:
    ...     def __init__(self):
    ...         self.some_value = 5
    

    then the value of some_value will be 5 and you don't have to set it when you create the object.

    >>> testobject = testing()
    >>> testobject.some_value
    5
    

    the >>> and ... in my sample is not what you write. It's how it would look in pyshell...

提交回复
热议问题