20.属性,类方法

1. #属性的装饰器
# class Bmi:
#
# def __init__(self,name,weight,height):
# self.name=name
# # self.__weight = weight if type(weight) is int else return '输入格式有误,请重新输入'
# self.__height=height
# @property #属性,将方法伪装成属性,是代码逻辑看起来更合理
# def wei(self):
# return '%s的BMI指数是%.2f'% (self.name,self.__weight/self.__height/self.__height)
#
# @wei.setter #属性的修改
# def wei(self,weight):
# if type(weight) is int:
# self.__weight=weight
# else:
# return '输入格式有误,请重新输入'
#
# @wei.deleter #属性的删除
# def wei(self):
# del self.__weight
# p1=Bmi('小明',60,1.85)
# p1.wei=56
# del p1.wei
# print(p1.__dict__)
# p1.bmi=65
# p1.a()
2.#类方法
# class Person:
# def work(self): #普通方法
# print(self)
# @classmethod
# def eat(cls): #类方法
# print(cls)
# p1=Person()
# p1.work() #对象调用普通方法 传进去的参数是对象空间
# p1.eat() #对象调用类方法,传进去的参数是对象所在的类空间

# 类方法的应用场景
#一.类中有些方法不需要对象参与
# class Person:
# country='诺克萨斯'
# people='卡特琳娜'
# @classmethod
# def func(cls):
# cls.a1=cls.country+cls.people
# Person.func()
# print(Person.__dict__)
#二.静态方法
# class A:
#
# @staticmethod
# def login(username, password):
# if username == 'alex' and password == 123:
# print('登录成功')
# else:
# print('登录失败...')


# A.login('alex',1234)
# a1=A()
# a1.login('alex',123) #类和对象都能调用,但一般对象只用来调用普通方法
#静态方法主要作用
# 1,代码块.看起来更加清晰.
# 2,复用性.
# 3.做实际应用中一个无主的函数会显得杂乱,故而将其封装在类中可以使代码更有可读性

#三.继承中,父类得到子类的类空间,(通过子类的对象也能得到子类的类空间的任意值,但不能改变子类的类属性)

# class Person:
# name='小明'
# @classmethod
# def func(cls):
# cls.name ='诺克萨斯'
# class Game(Person):
# name = '德玛西亚'
#
# g1=Game()
# g1.func()
# print(Game.__dict__)

猜你喜欢

转载自www.cnblogs.com/luxiangyu111/p/9378554.html