I am trying to learn the difference between the instance attributes and class attributes and attributes. I have the code below and I am trying to distinguish these factors.
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()
From what I understood the attributes would be: firstname,lastname,ucid,department,nationality,courses
But I do not know what instance attributes
and class attributes
would be.
I am trying to learn the difference between the instance attributes and class attributes and attributes.
there should be two attributes, class attribute
, instance attribute
. or instance attribute
&none-instance attribute
for convenience.
instance attribute
__init__
has been called.self.xxx
.self
as its first parameter(normally), these functions are instance methods, and you can only access after you initialized the Class.@property
deco, they are instance attributescommon 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
or static attribute
, whatever you call it
__init__
, even in __new__
.Class
and instance
.common seen class attribute
class Name(object):
attr = 'Im class attribute'
there is something else you may should know, class method
, which stay activated along with Class but the difference is class method
can't be called by instance but only Class. example here
class Name(object)
attr = 'Im class attribute'
@classmethod
def get_attr(cls):
return cls.attr
"class attribute" can be called by both instance and Class
"instance attribute" can only called by instance.