Say I have a class definition which takes some arguments and creates additional data with it, all within the __init__
method:
class Foo():
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
self.bar = generate_bar(x, y, z)
def generate_bar(self, x, y, z):
return x+y+z
I only want to run the generate_bar()
method once, when an instance of the class is created, so it wouldn't make sense for that method to be callable on the instance. Is there a sleeker way to ensure that a method is only available to __init__
, or do I just have to assume anyone who looks at my code will understand that there's never a situation in which it would be appropriate to call generate_bar() on an instance of the class?
If you are not using any instance state, just make it a separate function:
def _generate_bar(x, y, z):
return x + y + z
class Foo():
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
self.bar = _generate_bar(x, y, z)
The leading underscore, by convention, signals it is an internal function not to be used by external consumers of your module.
You could nest the function inside the __init__
but this doesn't really help with readability:
class Foo():
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def generate_bar():
return x + y + z
self.bar = generate_bar()
Here generate_bar()
doesn't even need arguments, it could access x
, y
and z
from the enclosing scope.
For "hidden" functions, it is customary to use a single underscore to signify your intent:
def _generate_bar(self, x, y, z): ...
These are still accessible, but are not visible via tab completion.
See this SO explanation :
class foo:
def __init__(self):
self.response = self._bar()
def _bar(self):
return "bar"
f = foo()
>>> f.response
bar
You can verify yourself that the function _bar is not visible to the object via tab completion
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.