简体   繁体   English

在哪里定义仅在__init__内部使用且不能在其他任何地方调用的方法?

[英]Where to define a method that is used only inside __init__ and must not be called anywhere else?

class Line(object):
    def __init__(self):
        self.length = None
        self.run_equation()

    def run_equation(self):
        # it runs through a formula then assigns the end value to length
        self.length = 50 # 50 for example

Now I want to populate a list with few Line objects. 现在,我想用几个Line对象填充一个列表。 The thing is I dont want run_equation() to be called ever again becouse I allready assigned the attribute inside __init__ , and it's value must not be changed. 事情是我不想再次调用run_equation() ,因为我已经在__init__内分配了属性,并且它的值一定不能更改。

What approaches should I follow, or do I have to stick this mind and simply not calling the method from the instance? 我应该遵循什么方法,或者我必须坚持这一思路,而不必从实例中调用该方法?

PS: Didn't find much on google or I just don't know how to search for this question. PS:在Google上找不到很多,或者我只是不知道如何搜索这个问题。

Python tries to hide methods and data that start with 2 underbars from outside users. Python尝试从外部用户隐藏以2个下划线开头的方法和数据。 Its not perfect, but the underbars tell programmers that you really don't want them to fiddle with them. 它并不完美,但是下划线告诉程序员您确实不希望他们摆弄它们。 Add a property to get a read only view of length, and I think you'll have what you want: 添加一个属性以获取长度的只读视图,我想您将拥有所需的内容:

class Line(object):
    @property
    def length(self):
        """The length of the line"""
        return self.__length

    def __init__(self):
        """Create a line"""
        self.__length = None
        self.__run_equation()

    def _run_equation(self):
        self.__length = 50

A trial run shows limited access 试运行显示访问受限

>>> from line import Line
>>> l=Line()
>>> l.length
50
>>> l.length = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
>>> l.__length = 1
>>> l.__run_equation()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Line' object has no attribute '__run_equation'
>>> l.length
50

>>> help(Line)
Help on class Line in module line:

class Line(__builtin__.object)
 |  Methods defined here:
 |  
 |  __init__(self)
 |      Create a line
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  length
 |      The length of the line

If there's only a single place where this is used—in __init__ —then you don't need a separate method to begin with. 如果在__init__只有一个地方使用它,那么您就不需要单独的方法了。 Just put the contents of that method into your __init__ directly: 只需将该方法的内容直接放入__init__即可:

class Line (object):
    def __init__ (self):
        self.length = 50

It's possible to define a function inside another function, and it will only be visible from the containing function: 可以在另一个函数中定义一个函数,并且该函数只能从包含的函数中看到:

def example():
    def pointless_function():
        print("Why do I exist, again?")
    pointless_function()

example()
pointless_function()

You could get rid of it once you're done: 完成后,您可以摆脱它:

class Line(object):
    def __init__(self):
        self.length = None
        self.assign_value_to_length()
        self.assign_value_to_length = None

    def assign_value_to_length(self):
        self.length = 50

This isn't very good practice, though. 不过,这不是很好的做法。 Instead, I'd just add an assertion: 相反,我只是添加一个断言:

    def assign_value_to_length(self):
        assert self.length is None
        self.length = 50

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 class 中定义只能从 __init__ 方法调用的方法 - How to define method in class that can only be called from __init__ method 在main方法内部调用的应用程序上实现的__init__方法 - __init__ method implemented on application called inside the main method Python __init__问题:必须以Bank实例作为第一个参数来调用未绑定方法__init __()(改为使用int实例) - Python __init__ issue: unbound method __init__() must be called with Bank instance as first argument (got int instance instead) 在__init__内作为else函数 - making a function as an else inside an __init__ Python-重写__init__的最简单方法,在super()调用之后必须使用可选的kwarg吗? - Python - Cleanest way to override __init__ where an optional kwarg must be used after the super() call? TypeError:未绑定方法__init __()必须以薪资实例作为第一个参数来调用(取而代之的是int实例) - TypeError: unbound method __init__() must be called with payroll instance as first argument (got int instance instead) 是什么导致“未绑定的方法__init __()必须使用实例作为第一个参数调用”来自此Python代码? - What is causing “unbound method __init__() must be called with instance as first argument” from this Python code? 未绑定的方法 __init__() 必须用...调用(但这没有意义...) - unbound method __init__() must be called with... (but it doesn't make sense...) 未绑定方法__init __()必须以CreditCard实例作为第一个参数调用(取而代之的是VisaCreditCard实例) - unbound method __init__() must be called with CreditCard instance as first argument (got VisaCreditCard instance instead) 错误:TypeError:未绑定方法__init __()必须以shape实例作为第一个参数调用(代替str实例) - # Error: TypeError: unbound method __init__() must be called with shape instance as first argument (got str instance instead) #
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM