Python 简明教程
Python - Class Attributes
类内定义的属性或变量称为 Attributes 。属性提供了关于类包含的数据类型的信息。Python 中有两种类型的属性,即 instance attribute 和 class attribute 。
The properties or variables defined inside a class are called as Attributes. An attribute provides information about the type of data a class contains. There are two types of attributes in Python namely instance attribute and class attribute.
实例属性在 Python 类的构造函数中定义,并且对于类的每个实例是唯一的。此外,类属性在类的构造函数之外声明并初始化。
The instance attribute is defined within the constructor of a Python class and is unique to each instance of the class. And, a class attribute is declared and initialized outside the constructor of the class.
Class Attributes (Variables)
类属性是属于某个类的变量,并且其值在该类的所有实例中共享。对于类的每个实例,类属性保持不变。
Class attributes are those variables that belong to a class and whose value is shared among all the instances of that class. A class attribute remains the same for every instance of the class.
类属性是在类中定义但不在任何方法中的。它们不能在 init () 构造函数内初始化。除了对象之外,还可以通过类的名称访问它们。换言之,类及其对象都可以使用类属性。
Class attributes are defined in the class but outside any method. They cannot be initialized inside init() constructor. They can be accessed by the name of the class in addition to the object. In other words, a class attribute is available to the class as well as its object.
Accessing Class Attributes
对象名称后跟点号符号 (.) 用于访问类属性。
The object name followed by dot notation (.) is used to access class attributes.
Example
以下示例演示如何访问 Python 类的属性。
The below example demonstrates how to access the attributes of a Python class.
class Employee:
name = "Bhavesh Aggarwal"
age = "30"
# instance of the class
emp = Employee()
# accessing class attributes
print("Name of the Employee:", emp.name)
print("Age of the Employee:", emp.age)
Modifying Class Attributes
若要修改类属性的值,我们只需要为其分配新值,方法是使用类名称后跟点号符号和属性名称。
To modify the value of a class attribute, we simply need to assign a new value to it using the class name followed by dot notation and attribute name.
Example
在以下示例中,我们在 Employee 类中初始化了一个名为 empCount 的类变量。对于声明的每个对象, init () 方法都会自动调用。此方法会初始化实例变量,并将 empCount 加 1。
In the below example, we are initializing a class variable called empCount in Employee class. For each object declared, the init() method is automatically called. This method initializes the instance variables as well as increments the empCount by 1.
class Employee:
# class attribute
empCount = 0
def __init__(self, name, age):
self.__name = name
self.__age = age
# modifying class attribute
Employee.empCount += 1
print ("Name:", self.__name, ", Age: ", self.__age)
# accessing class attribute
print ("Employee Count:", Employee.empCount)
e1 = Employee("Bhavana", 24)
print()
e2 = Employee("Rajesh", 26)
Significance of Class Attributes
类属性很重要的原因如下−
The class attributes are important because of the following reasons −
-
They are used to define those properties of a class that should have the same value for every object of that class.
-
Class attributes can be used to set default values for objects.
-
This is also useful in creating singletons. They are objects that are instantiated only once and used in different parts of the code.
Built-In Class Attributes
每个 Python 类都保存有以下内建属性,它们可以通过点运算符进行访问,与其他属性无异 -
Every Python class keeps the following built-in attributes and they can be accessed using the dot operator like any other attribute −
-
dict − Dictionary containing the class’s namespace.
-
doc − Class documentation string or none, if undefined.
-
name − Class name.
-
module − Module name in which the class is defined. This attribute is "main" in interactive mode.
-
bases − A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.
Access Built-In Class Attributes
为了在 Python 中访问内建类属性,我们可以使用类名后跟一个点 (.),然后是属性名。
To access built-in class attributes in Python, we use the class name followed by a dot (.) and then attribute name.
Example
对于 Employee 类,我们正尝试访问所有内建类属性 -
For the Employee class, we are trying to access all the built-in class attributes −
class Employee:
def __init__(self, name="Bhavana", age=24):
self.name = name
self.age = age
def displayEmployee(self):
print ("Name : ", self.name, ", age: ", self.age)
print ("Employee.__doc__:", Employee.__doc__)
print ("Employee.__name__:", Employee.__name__)
print ("Employee.__module__:", Employee.__module__)
print ("Employee.__bases__:", Employee.__bases__)
print ("Employee.__dict__:", Employee.__dict__ )
Output
它将生成如下输出:
It will produce the following output −
Employee.__doc__: None
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: (<class 'object'>,)
Employee.__dict__: {'__module__': '__main__', '__init__': <function Employee.__init__ at 0x0000022F866B8B80>, 'displayEmployee': <function Employee.displayEmployee at 0x0000022F866B9760>, '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>, '__doc__': None}
Instance Attributes
如前所述,Python 中的实例属性是一个特定于类中的某个单独对象的变量。它在 init () 方法中进行定义。
As stated earlier, an instance attribute in Python is a variable that is specific to an individual object of a class. It is defined inside the init() method.
此方法的第一个参数为 self,使用此参数可以定义实例属性。
The first parameter of this method is self and using this parameter the instance attributes are defined.
Example
在以下代码中,我们将演示实例属性的工作原理。
In the following code, we are illustrating the working of instance attributes.
class Student:
def __init__(self, name, grade):
self.__name = name
self.__grade = grade
print ("Name:", self.__name, ", Grade:", self.__grade)
# Creating instances
student1 = Student("Ram", "B")
student2 = Student("Shyam", "C")
Instance Attributes Vs Class Attributes
下表展示了实例属性和类属性之间的差异 -
The below table shows the difference between instance attributes and class attributes −
SNo. |
Instance Attribute |
Class Attribute |
1 |
It is defined directly inside the init() function. |
It is defined inside the class but outside the init() function. |
2 |
Instance attribute is accessed using the object name followed by dot notation. |
Class attributes can be accessed by both class name and object name. |
3 |
The value of this attribute cannot be shared among other objects. |
Its value is shared among other objects of the class. |
4 |
Changes made to the instance attribute affect only the object within which it is defined. |
Changes made to the class attribute affect all the objects of the given class. |