1 属性
1.1 公有属性
1.1.1 书写语法规则
self.公有属性名
1.1.2 调用语法规则
对象名.公有属性名
1.1.3 示例代码
class Person():
p_num = 0
def __init__(self, name, age, sex, job):
self.name = name
self.age = age
self.sex = sex
self.job = job
def eat(self):
print("吃饭")
def __sleep(self):
print("睡觉")
def show_sleep(self):
self.__sleep()
chinese_teacher = Person("张三", 24, "男", "语文老师")
print(f"该对象的名字为: {chinese_teacher.name}")
1.1.4 运行截图
1.2 私有属性
1.2.1 书写语法规则
self.__私有属性名
1.2.2 调用&修改规则
使用get_私有属性名方法调用 语法如下:
def get_私有属性名(self):
return self.__私有属性名
使用set_私有属性名方法修改
def set_私有属性名(self,参数):
self.__私有属性名=参数
1.2.3 示例代码
class Person():
p_num = 0
def __init__(self, name, age, sex, job):
self.__name = name
self.age = age
self.sex = sex
self.job = job
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
def eat(self):
print("吃饭")
def __sleep(self):
print("睡觉")
def show_sleep(self):
self.__sleep()
chinese_teacher = Person("张三", 24, "男", "语文老师")
print(f"修改前: 该对象的名字为: {chinese_teacher.get_name()}")
chinese_teacher.set_name("张三丰")
print(f"修改后: 该对象的名字为: {chinese_teacher.get_name()}")
1.2.4 运行截图
2 方法
2.1 公有方法
2.1.1 书写语法规则
def 公有方法名(self,参数1,参数2...参数n):
2.1.2 调用语法规则
对象名.公有方法名(参数1,参数2...参数n)
2.1.3 示例代码
class Person():
p_num = 0
def __init__(self, name, age, sex, job):
self.__name = name
self.age = age
self.sex = sex
self.job = job
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
def eat(self):
print("吃饭")
chinese_teacher = Person("张三", 24, "男", "语文老师")
chinese_teacher.eat()
2.1.4 运行截图
2.2 私有方法
2.2.1 书写语法规则
def __私有方法名(self,参数1,参数2...参数n):
2.2.2 调用语法规则
def 公有方法名(self):
self.__私有方法名()
对象名.公有方法名(self)
2.2.3 示例代码
class Person():
p_num = 0
def __init__(self, name, age, sex, job):
self.__name = name
self.age = age
self.sex = sex
self.job = job
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
def eat(self):
print("吃饭")
def __sleep(self):
print("睡觉")
def show_sleep(self):
self.__sleep()
chinese_teacher = Person("张三", 24, "男", "语文老师")
chinese_teacher.show_sleep()
2.2.4 运行截图