首页 > 解决方案 > 类属性和实例属性

问题描述

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

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是什么。

标签: pythonfunctionoopattributesinstance-variables

解决方案


我正在尝试了解实例属性与类属性和属性之间的区别。

应该有两个属性,class attribute, instance attribute。或instance attribute&none-instance attribute为方便起见。

instance attribute

  • 这些是只有在__init__被调用时才会激活的东西。
  • 只有在 Class 初始化后才能访问它们,通常称为self.xxx.
  • 和类中的方法self作为它的第一个参数(通常),这些函数是实例方法,你只能在你初始化类之后访问。
  • 和带有@property装饰的类中的方法,它们是实例属性
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 attribute或者static attribute,不管你怎么称呼它

  • 这些东西与 Class 一起保持激活状态。
  • 这意味着您可以在需要时访问它们,例如__init__,甚至在__new__.
  • 它们可以被Class和调用instance
common seen class attribute 

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

还有一些你可能应该知道的东西class method,它与 Class 一起保持激活状态,但不同之处在于class method不能通过实例调用,而只能通过 Class 调用。这里的例子

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

结论

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

“实例属性”只能通过实例调用。


推荐阅读