成人的BMI数值:
过轻:低于18.5
正常:18.5-23.9
过重:24-27
肥胖:28-32
非常肥胖, 高于32
体6质指数(BMI)=体重(kg)÷身高^2(m)
EX:70kg÷(1.75×1.75)=22.86
class People:
def __init__(self,name,weight,height):
self.name = name
self.weight = weight
self.height = height
# 定义函数的原因:
1、从bmi的公式上看,bim应该是触发动态功能计算得到的
2、bmi是随着身高,体重变化而动态变化的,不是一个固定的值
但是bmi听起来更像是一个数据属性,而非功能,所以添加@property
@property
def bmi(self):
my = (self.hegight**2)
return my
obj1 = People(‘liu‘,70,1.82)
print(obj1.bmi()) # 不加@property
print(obj1.bmi) #加@property
# 查 改 删
class People: #父类
def __init__(self,name):
self.__name = name
def get_name(self):
return self.__name # 直接返回查的结果
def set_name(self,val):
if type(val) is not str:
print(‘str类型‘)
return # 返回结果
self.__name = val # 赋值更改结果
def del_name(self):
print(‘不准删‘)
name = property(get_name,set_name,del_name)
# 调用
obj1 = People(‘liu‘)
obj1.name = ‘LIU‘ # 让更改看起来可像全局一样 直接赋予
class People:
def __init__(self,name)
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self,val):
if type(val) is not str:
print(‘必须为字符串类型‘)
return
self.__name = val
@name.deleter
def name(self):
print(‘不准删‘)
obj = People(‘liu‘)
print(obj.name) #liu
obj.name = ‘LIU‘
print(obj.name) #LIU
1、继承是一种创建新类的方式,新建的类可称为子类或者派生类,父类又可称为基类或者超类
python支持多继承,新建的类可以继承一个或多个父类
优点:可以遗传多个父类的属性,最大限度的重用代码
缺点:违背了人的思维习惯
代码的可读性变差(分支较多)
不建议使用多继承,可能会引发可恶的菱形问题 扩展性变差
真的涉及到了不可避免的多继承,应该使用mixins机制
class Student:
school = ‘北大‘
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def choice_course(self):
print(‘%s 选课中‘ %self.name)
class Teacher:
school = ‘北大‘
def __init__(self,name,age,sex,level,salary)
self.name = name
self.age = age
self.sex = sex
self.level = level
self.salary = salary
def score(self):
print(‘%s 正在打分‘ %self.name)
# Student和Teacher之间 name,age,sex 函数产生了冗余的问题
class People:
school = ‘北大‘
def __init__(self,name,age,sex): 共有的属性在父类里面定义
self.name = name
self.age = age
self.sex = sex
class Student(People):
def choose_course(self):
print(‘%s 正在选课‘ %self.name)
class Teacher(People):
def __init__(self,name,age,sex,level,salary) # Teacher 需要的属性
# 和父类要__init__
People.__init(self,name,age,sex)
self.level = level
self.salary = salary
def score(self):
print(‘%s 正在打分‘ %self.name)
tea_obj = Teacher(‘xxx‘,18,‘xx‘,12000,10)
tea_obj.score()
print(tea_obj.name) xxx
class Foo:
def f1(self):
print(‘Foo.f1)
def f2(self)
print(‘Foo.f2‘)
self.f1() --> # Bar.f1
class Bar(Foo):
def f1(self):
print(‘Bar.f1‘)
obj = Bar()
obj.f2() --> Foo.f2
class Foo:
def __f1(self):
print(‘Foo.f1)
def __f2(self):
print(‘Foo.f2)
self.__f1()
class Bar(Foo):
def f1(self):
print(‘Bar.f1‘)
obj = Bar()
obj.f2()
原文:https://www.cnblogs.com/liuyang521/p/14263856.html