类属性和实例属性

2024-05-16 00:55:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图了解实例属性和类属性以及属性之间的区别。我有下面的代码,我试图区分这些因素

class Student:
    firstname = ""
    lastname = ""
    ucid = ""
    department = ""
    nationality = ""
    courses = {}

    def __init__(self, fname, lname, ucid, dept, n):
        self.firstname = fname
        self.lastname = lname
        self.ucid = ucid
        self.department = dept
        self.nationality = n
        self.courses = {}

    def setName(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def setDepartment(self, d):
        self.department = d

    def setUcid(self, u):
        self.ucid = u

    def setNationality(self, n):
        self.nationality = n

    def addCourse(self, coursename, gpa):
        self.courses[coursename] = gpa

    def printAll(self):
        print("The name of the student is ", self.firstname, self.lastname)
        print("nationality and UCID: ", self.nationality, self.ucid)
        print("Department: ", self.department)
        print("Result: ")
        for key in self.courses.keys():
            print(key, self.courses[key])

        print("--------------------\n")

s1=Student("Beth","Bean","30303","Computer Science","International")
s1.addCourse("SCIENCE",3.75)
s1.printAll()
s2=Student("Mac","Miller","30303","Envr Science","American")
s2.addCourse("MATH",4.00)
s2.printAll()

据我所知,这些属性是:firstname,lastname,ucid,department,nationality,courses,但我不知道instance attributesclass attributes是什么


Tags: self属性deffirstnamefnamestudentdepartmentprint
1条回答
网友
1楼 · 发布于 2024-05-16 00:55:51

I am trying to learn the difference between the instance attributes and class attributes and attributes.

应该有两个属性,class attributeinstance attribute。或{}&none-instance attribute为了方便

instance attribute

  • 这些东西只有在调用__init__时才被激活
  • 您只能在类初始化后访问THNM,这通常被视为self.xxx
  • 和类中以self作为其第一个参数的方法(通常情况下),这些函数是实例方法,只有在初始化该类后才能访问
  • 类中的方法,它们是实例属性
common seen instance attribute 

class Name(object):
   def __init__(self):
        self.age = 100
   def func(self):
       pass
   @property
   def age(self):
       return self.age

class attribute

non-instance attributestatic attribute,不管你怎么称呼它

  • 这些东西在课堂上保持活跃
  • 这意味着您可以随时访问它们,比如__init__,甚至在__new__
  • 它们可以被Classinstance调用
common seen class attribute 

class Name(object):
   attr = 'Im class attribute'

您可能还应该知道class method,它与类一起保持激活状态,但区别在于class method不能由实例调用,只能由类调用。这里的例子

class Name(object)
   attr = 'Im class attribute'
   @classmethod
   def get_attr(cls):
       return cls.attr

结论

实例和类都可以调用“类属性”

“实例属性”只能由实例调用

相关问题 更多 >