【问题标题】:Changing the value of a class attribute using an instance [duplicate]使用实例更改类属性的值[重复]
【发布时间】:2023-01-08 20:46:11
【问题描述】:

我正在学习 python 中的类和对象。当我试图创建一个可以使用该类的实例更改其值的类属性时,我遇到了一个问题。 让我们假设为上同一所学校的学生创建一个班级 Student:

class Students:
    school = "Elimu"
    def __init__(self, name = "", class= 1):
        self.name = name
        self.class = class

student_1 = Students("Imara", 5)
student_2 = Students("Jabali", 7)

我希望能够使用类名和使用类的实例来更改类属性,即 class_name.class_attribute = new_value class_instance.class_attribute = new_value

为了进一步说明(在前面的代码之后):

Student.school
Student.school = "Ganjoni"
Student.school
student_1.school = "Vikwale"
Student.school
student1.school
student2.school

输出:

以利木
Ganjoni
维夸莱
维夸莱
维夸莱

【问题讨论】:

  • self.class = class 应该抛出语法错误。不是吗?
  • 请在示例中发布一些工作代码。您混合了很多班级名称和变量:Students 与 Student、student_1 与 student1。另外 class 是 python 中的关键字,所以你的 def __init__(self, name = "", class= 1): 将不起作用。
  • student_1.school = "Vikwale" 更改实例变量而不是类变量

标签: python python-3.x python-class class-attributes


【解决方案1】:

我假设你发布这个问题是因为 python 给了你某种错误(将你得到的错误添加到你的问题中很重要)。如果是这样,错误的原因是因为你试图使用“class”这个词作为属性,这是不允许的,因为“class”是一个关键字,以下是python的关键字列表:(我从https://www.w3schools.com/python/python_ref_keywords.asp 中获取了以下数据)

(图片来源https://www.resourcenote.info/2020/02/python-overview.html

所以任何作为关键字的词都不能用作变量名、函数名、类名、类属性名、函数输入参数名等。这些名字是神圣的。

class Students:
    school = "Elimu"
    def __init__(self, name = "",  ̶c̶l̶a̶s̶s̶ = 1):
        self.name = name
        self. ̶c̶l̶a̶s̶s̶ =  ̶c̶l̶a̶s̶s̶

student_1 = Students("Imara", 5)
student_2 = Students("Jabali", 7)

所以在上面的代码中,我删除了“class”的错误使用,用其他东西替换它或添加一些东西“sh_class”会做,或者任何它不能成为“class”的东西。

【讨论】:

    【解决方案2】:

    我不认为这是故意的,但你不能使用 class 作为有效的参数名称,因为它是一个关键字。

    这里应该注意的是,python 对其静态属性并不严格(与大多数其他编程语言不同),因为它真的不在乎你是否更改它,它总是会创建该属性的新实例它只会使用您设置的特定值,即直接更改它

    Students.school = "Some other school"
    

    只是要让它之后创建的所有类的默认值都为“其他学校”。这意味着您不能从单个实例更改所有其他类的值,也不能从主类更改之前创建的类的所有值。所以:

    Students.school = "a"
    studentOne = Students() # <- studentOne is going to have a default school attribute a
    Students.school = "b"   # <- doesn't change the value of studentOnes school
    studentTwo = Students() # <- but makes it so now any instance afterwards is going to have a default school value of "b"
    

    同样适用于:

    studentOne.school = "c" # <- doesn't change studentTwo's school value or the main classes school value
    

    【讨论】:

      猜你喜欢
      • 2018-04-17
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 2017-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多