class student:
grade = 10
#instantiate attribute
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
obj1 = student("a", 2, 9)
print(obj1.grade, obj1.name, obj1.age)
How can I access the grade in the class attribute
Use student.grade
(use the actual class name) to do that. However, it's bad habit to have two variables with the same name to do different things as it is bound to create confusion.
The outermost grade
variable is static and it's same for all instances of student
class. You can access it via student.grade
or obj1.grade
. But, in above case, instance variable overrides the global static variable.
If you want to access it via class instance(ie obj1.grade
), you need to rename local variable to something else.
ps: Generally, it's not good practice to use static variable whenever possible.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.