Private Constructor in Python

前端 未结 8 2002
栀梦
栀梦 2020-12-13 23:19

How do I create a private constructor which should be called only by the static function of the class and not from else where?

8条回答
  •  孤街浪徒
    2020-12-13 23:36

    Fist of all, the term "constructor" does not apply to Python, because, although __init__() method plays a role of one, it is just a method which is called when an object has already been created and requires initialization.

    Every method of a class in Python is public. Generally programmers mark "private" methods with _ or __ in the name of a method, e.g.:

    # inheriting from object is relevant for Python 2.x only
    class MyClass(object): 
        # kinda "constructor"
        def __init__(self):
            pass
    
        # here is a "private" method
        def _some_method(self):
            pass
    
        # ... and a public one
        def another_method(self):
            pass
    

提交回复
热议问题