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
现在我想填充一个包含少量Line
个对象的列表。
事情是我不想再次调用run_equation()
因为我已经在__init__
内分配了属性,并且它的值不能更改。
我应该遵循什么方法,或者我是否必须坚持这一点而不是从实例中调用方法?
PS:在Google上找不到多少,或者我只是不知道如何搜索这个问题。
答案 0 :(得分:2)
Python尝试隐藏以外部用户的2个下划线开头的方法和数据。它并不完美,但是下面的工具会告诉程序员你真的不想让它们摆弄它们。添加一个属性以获取长度的只读视图,我想你会得到你想要的东西:
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
试运行显示访问受限
>>> 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
答案 1 :(得分:1)
如果在__init__
中只使用了一个地方 - 那么您不需要单独的方法来开始。只需将该方法的内容直接放入__init__
:
class Line (object):
def __init__ (self):
self.length = 50
答案 2 :(得分:1)
可以在另一个函数中定义一个函数,它只能从包含函数中看到:
def example():
def pointless_function():
print("Why do I exist, again?")
pointless_function()
example()
pointless_function()
答案 3 :(得分:0)
一旦你完成,你就可以摆脱它:
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
但是,这不是一个很好的做法。相反,我只是添加一个断言:
def assign_value_to_length(self):
assert self.length is None
self.length = 50