zoukankan      html  css  js  c++  java
  • 面向对象基础(四)

    # 封装中的属性
    # 一个人是否健康可以通过bmi值来判断
    
    class Person:
        def __init__(self,name,height,weight):
            self.name = name
            self.height = height
            self.weight = weight
    
        def bmi(self):
            return '{name}的bmi值为{date}'.format(name = self.name,date = round(self.weight / self.height ** 2,1))
    
    p1 = Person('Tian',1.70,60)
    print(p1.bmi())
    
    # 这里bmi是一个名词一个属性的概念,这样调用是非常不符合规则的
    class Person:
        def __init__(self,name,height,weight):
            self.name = name
            self.height = height
            self.weight = weight
        # 加上装饰器之后bmi方法就成为了属性方法
        @property
        def bmi(self):
            return '{name}的bmi值为{date}'.format(name = self.name,date = round(self.weight / self.height ** 2,1))
    
    p1 = Person('Tian',1.70,60)
    print(p1.bmi)
    # 属性是可以更改的但是这里我们是一个伪装的属性所以无法更改,对此python中还有一些其他的装饰器
    class Person:
        def __init__(self,name,height,weight):
            self.name = name
            self.height = height
            self.weight = weight
            self.__bmi = round(self.weight / self.height ** 2, 1)
        @property
        def bmi(self):
            return '{name}的bmi值为{date}'.format(name = self.name,date = self.__bmi)
    
        @bmi.setter
        def bmi(self,num):
            self.__bmi = num
    
        @bmi.deleter
        def bmi(self):
            del self.__bmi
    p1 = Person('Tian',1.70,60)
    p1.bmi = 10
    print(p1.bmi)
    del p1.bmi
    # 这样就可以修改了,当然这种写法是不规范的没人会在构造函数做计算,这里只是以此举例
    # 类方法
    class A:
        count = 20
    
        @classmethod
        def cal(cls,num):
            return num + cls.count
    
    # 这一类无需对象参与的的方法可以用类方法
    print(A.cal(15))
    
    
    
    # 父类要获取派生类也可以用类方法
    class B(A):
        count = 30
    print(B.cal(15))
    # 类中的静态方法
    
    class A:
        @staticmethod
        def func(user,pwd):
            if user == 'Tian' and pwd == 666:
                print('success')
            else:
                print('error')
    
    
    A.func('Tian',666)
    
    # 增加代码的复用性
    # 使代码块更加整洁明了
  • 相关阅读:
    几个新角色:数据科学家、数据分析师、数据(算法)工程师
    人类投资经理再也无法击败电脑的时代终将到来了...
    Action Results in Web API 2
    Multiple actions were found that match the request in Web Api
    Routing in ASP.NET Web API
    how to create an asp.net web api project in visual studio 2017
    网站漏洞扫描工具
    How does asp.net web api work?
    asp.net web api history and how does it work?
    What is the difference between a web API and a web service?
  • 原文地址:https://www.cnblogs.com/tengx/p/11888431.html
Copyright © 2011-2022 走看看