类与对象
定义类
初始化函数中,self后面的是实例化对象的属性。
加下划线代表这个属性是私有的,不应该被外界直接访问
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
def hello(self):
print("My name is {}, age is {}".format(self._name, self._age))
person = Person("xiaobai")
person.hello()
继承
class Student(Person):
# pass # 表示什么也不做, 占位而已
def set_score(self, score):
self._score = score
def get_score(self):
return self._score
@property
def grade(self):
return self._grade
def set_grade(self, grade):
self._grade = grade
student = Student("xiaoming", 7)
student.hello()
student.set_score(100)
print(student.get_score())
student.set_grade("三年级")
print(student.grade)
代码
print("--------------- 定义类 ---------------")
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
def hello(self):
print("My name is {}, age is {}".format(self._name, self._age))
person = Person("xiaobai", 18)
person.hello()
print("--------------- 继承 ---------------")
class Student(Person):
# pass # 表示什么也不做, 占位而已
def set_score(self, score):
self._score = score
def get_score(self):
return self._score
@property
def grade(self):
return self._grade
def set_grade(self, grade):
self._grade = grade
student = Student("xiaoming", 7)
student.hello()
student.set_score(100)
print(student.get_score())
student.set_grade("三年级")
print(student.grade)
"""
输出:
--------------- 定义类 ---------------
My name is xiaobai, age is 18
--------------- 继承 ---------------
My name is xiaoming, age is 7
100
三年级
"""