Python 中的类属性与实例属性类
2023-09-19 15:29:51
属性是直接在类中定义的变量,由类的所有对象共享。
实例属性是附加到类实例的属性或属性。 实例属性在构造函数中定义。
下表列出了类属性和实例属性之间的区别:
Class Attribute | Instance Attribute |
---|---|
直接在类中定义。 | 使用 self 参数在构造函数中定义。 |
在所有对象之间共享。 | 特定于对象。 |
使用类名以及使用带有点符号的对象进行访问,例如 classname.class_attribute 或object.class_attribute | 使用对象点表示法访问,例如 object.instance_attribute |
使用 classname.class_attribute = value 更改值将反映到所有对象。 | 实例属性值的更改不会反映到其他对象。 |
下面的示例演示如何使用类属性count
。
示例: Student.py
class Student:
count = 0
def __init__(self):
Student.count += 1
在上面的示例中,count
是 Student 类中的一个属性。
每当创建新对象时,count
的值都会递增 1。
现在,您可以在创建对象后访问 count
属性,如下所示。
示例:
>>> std1=Student()
>>> Student.count
1
>>> std2 = Student()
>>> Student.count
2
下面演示实例属性。
示例: Setting Attribute Values
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
现在,您可以在创建实例时指定值,如下所示。
示例: Passing Instance Attribute Values in Constructor
>>> std = Student('Bill',25)
>>> std.name
'Bill'
>>> std.age
25
>>> std.name = 'Steve'
>>> std.age = 45
>>> std.name
'Steve'
>>> std.age
45
访问Python Class了解更多信息。