python - object oriented (OOP- class)


  1. Instantiation 
  2. Constructor 
  3. Initialization 
  4. Instances 
  5. Override

class University:
    School_num = 0 #class variable shared in all instances of this class
    __passward = 123 #doesn't visible outside the class
    def __init__(self, name, tuition):#constructor or initialization
        self.name = name
        self.tuition = tuition
        University.School_num += 1   #access class variable

    def print_School_num(self):
        print ("Total School ",University.School_num)

    def print_tuition(self):
        print ("University : ", self.name,  ", tuition: ", self.tuition)
    def __del__(self):
        print ( 'class name : "', self.__class__.__name__, '" destroyed by Garbage Collection' )

NTUST = University('NTUST', 23140)#create instances
TKU = University('TKU', 54200)#create instances
NTUST.print_tuition()
TKU.print_tuition()
#tuition increase
NTUST.tuition = 31200
NTUST.print_tuition()
#doesn't need tuition
del NTUST.tuition
class senior_school(University): #Inheritance University
    def Get_age(self):
        print ('under 18')
    def print_tuition(self): #override 
        print ("senior_school : ", self.name,  ", tuition: ", self.tuition)

YLSH = senior_school('YLSH', 12345)
YLSH.Get_age()#call function form own(child)
YLSH.print_School_num()#call function that Inheritance from parent , and share class variable with parent
YLSH.print_tuition()#call override function
result
University :  NTUST , tuition:  23140
University :  TKU , tuition:  54200
University :  NTUST , tuition:  31200
under 18
Total School  3
senior_school :  YLSH , tuition:  12345
class name : " University " destroyed by Garbage Collection
class name : " University " destroyed by Garbage Collection
class name : " senior_school " destroyed by Garbage Collection

留言