Skip to content

Attribute

一句话解释

attribute 是 named 值 存储 on 对象, accessed 使用 点 notation (obj.attribute).

用大白话说

attribute 是片段的 数据存储 on 对象. 你 access 它使用点 notation: obj.attribute. Attributes 是典型地设置 in __init__ using self.name = value.

There are two kinds of attributes: instance attributes (unique to each object, set with self) and class attributes (shared by all instances, set on the class itself). Instance attributes are more common.

You can add, modify, or delete attributes at any time using dot notation. Python objects are flexible — you can even add attributes that weren't defined in __init__. Use hasattr(obj, 'name') to check if an attribute exists, and getattr(obj, 'name', 默认) for safe access.

示例

python
class Person:
    species = "Homo sapiens"  # class attribute

    def __init__(self, name):
        self.name = name  # instance attribute

p = Person("Alice")
print(p.name)       # Alice (instance attribute)
print(p.species)    # Homo sapiens (class attribute)

p.age = 30  # dynamically added attribute
print(p.age)  # 30

Attributes 是 对象 数据 accessed 使用 点 notation. 实例 attributes 是 每-对象; 类 attributes 是 shared.

常见混淆

  • 容易混淆的对象: 方法

    关键区别: attribute 是 数据 值 存储 on 对象 (obj.name). 方法 是 函数 存储 on 对象 (obj.方法()). Attributes 是 accessed 不使用 parentheses; 方法 是 called 使用 parentheses.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表