+
and -
symbols declare
whether a variable or function is public or
privateclass
keyword followed by the name you want to give itstudent1.name = Ian
__init__()
__init__()
is called automatically each
time the class has been used to create a new objectstudent1.name = Ian
student1.age = 33
student2.name = Terry
student2.age = 1
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def greeting(self):
return "Hello " + self.name + " and welcome to 4061CEM!"
student1.greeting() = Hello Ian and welcome to 4061CEM!
[Before] student1.age = 33
[After] student1.age = -1
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def change_age(self, new_age):
self.age = new_age
[Before] student1.age = 33
[After] student1.age = -1
__
’) to the beginning of the variable
nameclass Student:
def __init__(self, name, age):
self.__name = name
self.__age = age
def change_age(self, new_age):
self.__age = new_age
def get_age(self):
return self.__age
[Before] student1.get_age() = 33
[After] student1.get_age() = -1
del
keywordpass
keywordclass Student:
def __init__(self, name, age):
self.__name = name
self.__age = age
def change_age(self, new_age):
self.__age = new_age
def get_age(self):
return self.__age
def get_name(self):
return self.__name
def greeting(self):
return f"Hello {self.__name} and welcome to 4061CEM!"
student1.get_name() = Ian
student1.get_age() = 33
student1.greeting() = Hello Ian and welcome to 4061CEM!
person1.get_name() = Ian
person1.greeting() = Hello Ian and welcome to 4061CEM!
__init__
function to the
child class, it will no longer inherit the
__init__
function from the parent class__init__
function from the parent
classclass Person(Student):
def __init__(self, name, age, location):
Student.__init__(self, name, age)
self.location = location
person1.get_name() = Ian
person1.location = Coventry
super()
function, instead of using the parent
classes nameclass Person(Student):
def __init__(self, name, age, location):
super().__init__(name, age)
self.location = location
person1.get_name() = Ian
person1.location = Coventry
class Person(Student):
def __init__(self, name, age, location):
super().__init__(name, age)
self.location = location
def greeting(self):
return f"Hello {self.get_name()} and welcome to 4061CEM from {self.location}!"
person1.greeting() = Hello Ian and welcome to 4061CEM from Coventry!