属性和方法的Python命名约定将被覆盖 [英] Python naming conventions for attributes and methods meant to be overwritten

查看:89
本文介绍了属性和方法的Python命名约定将被覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中有一些面向对象的代码,其中的某些类应进行扩展以提供缺少的自定义代码(请模板方法模式,但也包含变量),该模式只会由超类使用,而不会由使用它们的客户端代码使用.

I have some object oriented code in Python, where some classes are meant to be extended to provide the missing custom bits of code (a la Template Method pattern, but also with variables), that will only be used by the super class, not by the client code using them.

这样的抽象(或枯燥,因为它们在超类中的实现是pass或引发NonImplemented异常)方法和属性是否存在任何样式约定?

Are there any style conventions for such abstract (or dull, because their implementation in the super class would be either pass or raise a NonImplemented exception) methods and attributes?

我一直在浏览 PEP-0008 ,并且仅提到将下划线加到不打算由子类使用的 private 成员上.

I've been browsing the PEP-0008 and it only mentions about prepending an underscore to private members not intended to be used by subclasses.

推荐答案

首先,我认为您说错了您的想法:

First of all i think that you are mistaken when you say that:

将下划线加到不打算由子类使用的私有成员上.

about prepending underscore to private members not intended to be used by subclasses.

实际上,在方法/属性前加下划线是python约定,这意味着不应在类(及其子类)之外访问此方法/属性,而且我认为您忘了阅读用于使无法覆盖的方法/属性.

Actually prepending a method/attribute by underscore is a python convention that mean that this method/attribute shouldn't be accessed outside the class (and its subclass) and I think you forgot to read about the double underscore that is used to make a method/attribute not possible to override.

class Foo(object):
    def __foo(self):
        print "foo"
    def main(self):
        self.__foo()


class Bar(Foo):
    def __foo(self):
        print "bar"


bar = Bar()
bar.main()
# This will print "foo" and not "bar".


还有一种使用 abc的方式声明存根方法的方法.ABCMeta abc.abstractmethod .

这篇关于属性和方法的Python命名约定将被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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