Python风格问题:支持类作为内部类吗?

发布于 2024-10-12 11:12:13 字数 543 浏览 4 评论 0原文

我喜欢使用语言内置的结构来组织我的代码。但在一种情况下,我无法保持一致,仅仅是因为我没有看到明确的最佳方法。它涉及支持类,即专门由另一个类在内部使用的类:我是否将它们设为内部类或单独的类。

内部类:

class Complicated:
    class Utility1:
        pass
    class Utility2:
        pass
    pass

单独的类:

class Complicated:
    pass

class Utility1:
    pass

class Utility2:
    pass

内部类的优点是其作用域位于唯一使用它们的类内。但问题是,由于缩进,我编写代码的空间更少。

外层阶级既没有优点也没有缺点。我厌倦了每当我写支持课程时总是花费一些精力来思考这个愚蠢的问题。

我的问题是,是否有丰富的Python经验的人可以建议是否有这方面的最佳实践?即使答案是“这取决于”,如果有比我更有经验的人来回答,我会很感激。

I like to use the structures built into the language to organize my code. But there is one situation where I can't stay consistent, simply because I don't see a definitive best way of doing it. It's regarding support classes, that is, classes that are exclusively used internally by another class: Do I make them inner classes, or separate classes.

Inner classes:

class Complicated:
    class Utility1:
        pass
    class Utility2:
        pass
    pass

Separate classes:

class Complicated:
    pass

class Utility1:
    pass

class Utility2:
    pass

Inner classes has the advantage of being scoped inside the only class that uses them. But the problem is that I get less space to write code due to indentation.

Outer classes have neither the advantage nor the disadvantage. I am tired of always spending some mental energy whenever I write support classes, wondering about this silly issue.

My question is whether anyone with a substantial python experience on their back can advise as to whether there is a best practice regarding this? Even if the answer is that "it depends", it is appreciated if it comes with someone more experienced than myself.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

差↓一点笑了 2024-10-19 11:12:13

我建议

class Complicated:
    pass

class _Utility1:
    pass

class _Utility2:
    pass

并将所有这些放入其自己的模块中。前导 _ 表示实用程序类仅供内部使用(并且就其价值而言,它们不会由 from module import * 导入;但我不知道反正不喜欢这样)。

编辑:引用 PEP 8

供内部使用的类还有一个前导下划线。

I would suggest

class Complicated:
    pass

class _Utility1:
    pass

class _Utility2:
    pass

and put all this in a module of its own. The leading _ indicates that the utility classes are meant for internal use only (and for what it's woth, they won't get imported by from module import *; but I don't like this anyway).

Edit: Citing from PEP 8:

Classes for internal use have a leading underscore in addition.

柳絮泡泡 2024-10-19 11:12:13

我使用单下划线作为 python 包内部类的前缀。我认为这是一个常见的 python 模式:

class Complicated:
    pass

class _Utility1:
    pass

class _Utility2:
    pass

I use the single underscore as a prefix to classes that are internal to a python packages. I think this is a common python pattern:

class Complicated:
    pass

class _Utility1:
    pass

class _Utility2:
    pass
清秋悲枫 2024-10-19 11:12:13

我是否使用内部类或外部类很大程度上取决于我是否希望在子类中或在每个实例的基础上重写类型:

class Foo(object):
    normalize = str

    def process(self, input):
        # Do some stuff in here...
        return self.normalize(output)

class UniFoo(Foo):
    normalize = unicode

class TotallyMungedFoo(Foo):
    class normalize(object): ...

如果我不希望需要(或明确不希望)像这样的行为为此,我在同一模块中使用类,但仅在我的 __all__ 声明中包含“重要”类。

Whether I use an inner class or outer class largely depends on whether I expect to override the type, either in a subclass or on a per-instance basis:

class Foo(object):
    normalize = str

    def process(self, input):
        # Do some stuff in here...
        return self.normalize(output)

class UniFoo(Foo):
    normalize = unicode

class TotallyMungedFoo(Foo):
    class normalize(object): ...

If I don't expect to need (or explicitly don't want) behavior like this, I use classes in the same module, but only include the "important" one in my __all__ declaration.

无敌元气妹 2024-10-19 11:12:13

Python 内部类

Python 内部类可以创建和使用。
与其他语言(例如 Java)不同,Python 内部类不会自动授予您对外部类属性和方法的访问权限。

此问题的解决方法:
使用父参数定义所有内部类。该参数可用于访问外部类的属性和方法。

带有内部类的 Python 示例类

class Outer:
    def __init__(self):
        self.myVar = 100
        self.inner = self.Inner(self)
        
    def getDoubleVar(self):
        return(self.myVar * 2)

    #Define inner class
    class Inner:
        def __init__(self, parent):
            self.parent = parent

        #Use the parent variable to access parent class attributes/methods
        def printOuterVar(self):
            print(self.parent.myVar)

        def callOuterMethod(self):
            return(self.parent.getDoubleVar())


    

#Create Instance of Outer Class
outer = Outer()

#Display myVar
print("Display myVar")
print(outer.myVar)


#Execute Outer Method
print("\nExecute Outer Method")
print("val = outer.getDoubleVar()")
val = outer.getDoubleVar()
print("val: {0}".format(val))

#Execute Inner Method
print("\nExecute Inner Method")
print("outer.inner.printOuterVar()")
outer.inner.printOuterVar()

#Execute Inner Method That Calls Outer Method
print("\nExecute Inner Method That Calls Outer Method")
val = outer.inner.callOuterMethod()
print("val = outer.inner.callOuterMethod()")
print("val: {0}".format(val))

#Create Instance of Inner Class Separately
print("\nInstantiate Inner Class Separately")
#Note that you provide the current outer instance as the parent parameter
print("Note that you provide the current outer instance as the parent parameter")
print("myInner = outer.Inner(outer)")
myInner = outer.Inner(outer)

#Call Inner Method
print("\nCall Inner Method")
print("myInner.printOuterVar()")
myInner.printOuterVar()
print("finished")

Python Inner Classes

Python inner classes are possible to create and use.
Unlike other languages, such as Java, Python inner classes don't automatically give you access to the outer class attributes and methods.

The work around for this problem:
Define all Inner Classes with a parent parameter. This parameter can be used to access the outer class attributes and methods.

Python Example Class with Inner Class

class Outer:
    def __init__(self):
        self.myVar = 100
        self.inner = self.Inner(self)
        
    def getDoubleVar(self):
        return(self.myVar * 2)

    #Define inner class
    class Inner:
        def __init__(self, parent):
            self.parent = parent

        #Use the parent variable to access parent class attributes/methods
        def printOuterVar(self):
            print(self.parent.myVar)

        def callOuterMethod(self):
            return(self.parent.getDoubleVar())


    

#Create Instance of Outer Class
outer = Outer()

#Display myVar
print("Display myVar")
print(outer.myVar)


#Execute Outer Method
print("\nExecute Outer Method")
print("val = outer.getDoubleVar()")
val = outer.getDoubleVar()
print("val: {0}".format(val))

#Execute Inner Method
print("\nExecute Inner Method")
print("outer.inner.printOuterVar()")
outer.inner.printOuterVar()

#Execute Inner Method That Calls Outer Method
print("\nExecute Inner Method That Calls Outer Method")
val = outer.inner.callOuterMethod()
print("val = outer.inner.callOuterMethod()")
print("val: {0}".format(val))

#Create Instance of Inner Class Separately
print("\nInstantiate Inner Class Separately")
#Note that you provide the current outer instance as the parent parameter
print("Note that you provide the current outer instance as the parent parameter")
print("myInner = outer.Inner(outer)")
myInner = outer.Inner(outer)

#Call Inner Method
print("\nCall Inner Method")
print("myInner.printOuterVar()")
myInner.printOuterVar()
print("finished")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文