Warm tip: This article is reproduced from serverfault.com, please click

python-类属性和实例属性

(python - Class Attributes and Instance Attributes)

发布于 2020-12-08 01:48:14

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

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会。

Questioner
haribo11
Viewed
11
tomy0608 2020-12-08 13:06:53

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

应该有两个属性,class attributeinstance attributeinstance attributenone-instance attribute为方便起见。

instance attribute

  • 这些只有在__init__被调用时才激活
  • 你只能在Class初始化后才能访问thenm,通常将其称为self.xxx
  • 以及self通常以第一个参数为类的类中的方法,这些函数是实例方法,并且只有在初始化Class后才能访问。
  • @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 attributestatic 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

结论

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

“实例属性”只能按实例调用。