# two ways without parameters classMyClass: i = 12345 deff(self): return'hello world' #the other way is instantiation classMyClass: def__init__(self): self.data = []
含参的类
1 2 3 4 5 6 7 8 9 10
classHigh_school_student(): school = "BUPT" def__init__(self,age,sex): self.age = age self.sex = sex studen1 = High_school_student(18,'M') print("The age of student is"+str(student1.age)) print(student1.school)
类的私有化
通过在属性成员的名称前加下滑线”__“实现成员的私有化
1 2 3 4 5 6
classHigh_school_student(): def__init__(self,age,sex) self.__age = age self.__aex = sex student1 = High_school_student(18,'M') print("The age of student is"+str(student.age))
得到的结果是
但是私有化成员并非不可访问,可以通过_类名__私有变量的方式来进行访问
另外除了属性成员(attribute references),方法(method)也可进行私有化
类的继承(Inheritance)
The syntax for a derived class definition looks like this: