【问题标题】:Why Dot Notation For "Method" Variables and Not For Others?为什么“方法”变量的点符号而不是其他变量?
【发布时间】:2015-06-17 21:46:20
【问题描述】:

假设我在 Python 中创建了以下类:

class SomeClass(object):
    variable_1 = "Something"
    def __init__(self, variable_2):
        self.variable_2 = variable_2 + self.variable_1

我不明白为什么位于方法定义之外的变量(我应该说是函数吗?),但在类的主体中,没有使用像variable_1 这样的点符号来命名,而方法定义中的变量被命名为 -例如:self.variable_2 - 或引用 - 例如:self.variable_1 使用点符号。这只是 Python 特有的符号还是出于其他原因?

【问题讨论】:

    标签: class python-2.7 methods attributes


    【解决方案1】:

    这在 C++ 或 java 中是找不到的。它不仅仅是一个符号。参见文档documentation

    类具有 Python 的动态特性:它们创建于 运行时,并且可以在创建后进一步修改。

    函数也是一样。

    这是定义类的有效方法:

    def f1(self, x, y):
        return min(x, x+y)
    
    class C:
        text = 'hello world'
        f = f1
        def g(self):
            return self.text
        h = g
    

    fghC的属性。为了使它工作,将对象作为函数的参数传递是很重要的。按照惯例,它被命名为self

    这是非常强大的。它允许真正使用函数作为属性。例如:

    c = C()
    class B:
        text = 'hello word 2'
        g = c.g
    

    B.g() 的调用将返回'hello word 2'。只有使用了self才有可能。

    作为记录,您还可以阅读global 和一般变量范围的文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-26
      • 2022-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多