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

查看:445
本文介绍了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?

推荐答案

术语

精神模型:

Terminology

Mental model:

  • 存储在实例或类中的变量被称为
  • A variable stored in an instance or class is called an attribute.
  • A function stored in an instance or class is called a method.

根据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天全站免登陆