python中方法和属性的区别 [英] Difference between methods and attributes in python

查看:21
本文介绍了python中方法和属性的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Python 并在做一个关于课程的练习.它告诉我将 nd 属性添加到我的类,并向我的类添加一个方法.在我阅读练习之前,我一直认为这些是同一回事.两者有什么区别?

I am learning python and doing an exercise about classes. It tells me to add nd attribute to my class and a method to my class. I always thought these were the same thing until I read the exercise. What is the difference between the two?

推荐答案

术语

心理模型:

  • 存储在实例或类中的变量称为属性.
  • 存储在实例或类中的函数称为方法.

根据 Python 的词汇表:

According to Python's glossary:

属性:与被引用的对象关联的值使用虚线表达式命名.例如,如果一个对象 o 有一个属性 a 将被引用为 o.a

attribute: A value associated with an object which is referenced by name using dotted expressions. For example, if an object o has an attribute a it would be referenced as o.a

方法: 在类体内定义的函数.如果被称为该类的实例的属性,该方法将获得实例对象作为它的第一个参数(通常称为 self).请参阅函数和嵌套作用域.

method: A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). See function and nested scope.

示例

应用于实际代码的术语:

Examples

Terminology applied to actual code:

a = 10                          # variable

def f(b):                       # function  
    return b ** 2

class C:

    c = 20                      # class attribute

    def __init__(self, d):      # "dunder" method
        self.d = d              # instance attribute

    def show(self):             # method
        print(self.c, self.d) 

e = C(30)
e.g = 40                        # another instance variable

这篇关于python中方法和属性的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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