出于组织目的在 Python 代码中强制缩进
Python 有没有办法强制缩进? 我想要它是为了让代码看起来更有条理。 举个例子:
# How it looks now
class Bro:
def __init__(self):
self.head = 1
self.head.eye = 2
self.head.nose = 1
self.head.mouth = 1
self.neck = 1
self.torso = 1
# How it'd look ideally (indenting sub-variables of 'head')
class Bro:
def __init__(self):
self.head = 1
self.head.eye = 2
self.head.nose = 1
self.head.mouth = 1
self.neck = 1
self.torso = 1
我想通过某种解决方法这是可能的,是吗?
Is there a way to force an indent in Python?
I kind of want it for the sake of making the code look organized.
As an example:
# How it looks now
class Bro:
def __init__(self):
self.head = 1
self.head.eye = 2
self.head.nose = 1
self.head.mouth = 1
self.neck = 1
self.torso = 1
# How it'd look ideally (indenting sub-variables of 'head')
class Bro:
def __init__(self):
self.head = 1
self.head.eye = 2
self.head.nose = 1
self.head.mouth = 1
self.neck = 1
self.torso = 1
I imagine this is possible with some sort of workaround, yeah?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能做这样的缩进,因为缩进用于解析Python代码块,而不仅仅是出于时尚的原因......
如果你想以某种方式对它们进行分组,您可以按如下方式使用字典:
但这不是一个好方法,因此在字典中定义所有身体部位更好
可能是更好的方法,但它更难使用,因为编写
self.nose
是比简单self.head.nose
或self.body['head']['nose']
You can not make a such indentation, because indentatin is used for parsing python code blocks, not simply just for stylish reasons...
If you want to group them somehow, the you can use a dict as follows:
but simply that is not a good way, so defining all body parts within dictionary is better
Might be a better approach, but its harder to use since writing
self.nose
is simpler thanself.head.nose
orself.body['head']['nose']
从技术上讲,是的,这是可能的,例如:
就可读性而言,这是否是一个好主意,我不确定。我个人可能不会这样做。
PS One 可能会使用(滥用?)
with
语句来使其可读性更好。Technically, yes it's possible, e.g.:
Whether that's a good idea as far as readability goes, I am not sure. I personally would probably not do it.
P.S. One could probably use (abuse?) the
with
statement to make it read better.