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 attributes
会class attributes
是什么。
解决方案
我正在尝试了解实例属性与类属性和属性之间的区别。
应该有两个属性,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
结论
实例和类都可以调用“类属性”
“实例属性”只能通过实例调用。
推荐阅读
- javascript - AXIOS PUT 请求返回 200 代码但不更新内容?
- angular - 从未调用过 Ionic 4 服务构造函数-> httpClient http.get 失败
- windows - 将 CMD 输出转换为 CSV 文件
- docker - 惯用的 Makefile 和命令参数
- c# - 如何释放被跟踪的实体?
- xamarin - 使用 MVVMCross 实现 UISearchController
- mysql - 如何从表格中获取最多评论的用户
- java - 运行时与 Twilio 的 Maven 子依赖冲突
- ios - 使用自定义 fillShader 加载 SKShapeNode 会导致程序挂起
- reactjs - 如何定义react方法的具体返回类型(打字稿)