出于组织目的在Python代码中强制缩进 [英] Force an indent in Python code for organizational purposes

查看:64
本文介绍了出于组织目的在Python代码中强制缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Python中强制缩进?为了使代码看起来井井有条,我有点想要它.例如:

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?

推荐答案

您不能进行这样的缩进,因为indentatin用于解析python代码块,而不仅仅是用于 stylish原因...

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:

class Bro:
    def __init__(self):
        self.head {
            'head': 1,
            'eye' : 2,
            'nose' : 1,
            'mouth' : 1,
        }
        self.neck = 1
        self.torso = 1

但是简单地说,这不是一个好方法,因此在字典中定义所有身体部位会更好

but simply that is not a good way, so defining all body parts within dictionary is better

class Bro:
    def __init__(self):
        self.body {
            'head': {
                'head': 1,#defining itself
                'eye' : 2,
                'nose' : 1,
                'mouth' : 1,
            },
            'neck' : 1,
            'torso' : 1, 
       }

可能是一种更好的方法,但是由于编写 self.nose self.head.nose self.body ['更简单,因此它更难使用.头'] ['鼻子']

Might be a better approach, but its harder to use since writing self.nose is simpler than self.head.nose or self.body['head']['nose']

这篇关于出于组织目的在Python代码中强制缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆