python之路---面向对象之绑定方法与特性property

绑定方法:

概念:绑定给谁,就应该由谁调用,由谁调用就将其作为第一个参数自动传入

分类:绑定给对象的--->在类内定义的函数,没有被装饰器修饰过的,默认就是绑定给对象使用的

     绑定给类的  ---->在类内定义的函数,被装饰器classmethod装饰过的就是绑定给类使用的 

注意:绑定给类的,就应该由类来调用,但是对象也可以调用,只不过自动传入的仍然是类

    绑定给对象的还是给类的,取决于函数体的代码需要谁,如果两者都不需要,则为非绑定

非绑定方法:

  概念:既不与类绑定也不与对象绑定(意味着对象和类都可以调用,但是都没有自动传值的效果)

             在类内定义的函数,被装饰器staticmethod装饰过的就是非绑定函数

import setting
import uuid


class People:
    def __init__(self,host, port):
        self.uuid = self.uuid()
        self.id = host
        self.port = port

    def info_in(self):
        print('IP地址:%s\t端口:%s\tuuid:%s' % (self.id, self.port, self.uuid))

    @classmethod
    def change(cls):
        return cls(setting.hsot, setting.port)

    @staticmethod
    def uuid():
        return uuid.uuid4()


p = People.change()
p.info_in()

特性property:

概念:可以将类内定义的函数伪装成数据属性去访问

class People:
    def __init__(self, name, weight, high):
        self.name = name
        self.weight = weight
        self.high = high

    @property
    def bmi(self):
        return 'BMI值为:%.2f' % (self.weight / (self.high ** 2))


tony = People('小马哥', 46, 1.7)
print(tony.bmi)
class People:
    def __init__(self, name, age):
        self.__name = name

    @property
    def information(self):
        return '姓名:%-5s' % self.__name

    @information.setter
    def information(self,name):
        self.__name = name

    @information.deleter
    def information(self):
        raise KeyError('小马哥 is tony,this fact cannot be changed!!!')


tony = People('小马哥', 26)
# print(tony.name, tony.age)
tony.information = 'bob'
del tony.information
print(tony.information)

此外,还可以通过property控制对象属性的更改(隐藏类的数据属性,然后提供接口,又将接口名伪装成数据属性,在用户毫无感觉的前提下,控制了用户对属性的直接操作)

class OperateError(BaseException):
    def __init__(self, msg):
        super().__init__()
        self.msg = msg

    def __str__(self):
        return self.msg


class Bar:
    def __init__(self, name):
        self.__name = name

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, value):
        if not isinstance(value, str):
            raise TypeError('类型错误,必须是字符串!')
        self.__name = value

    @name.deleter
    def name(self):
        raise OperateError('操作错误,属性不能被删除!!!!!!')


student = Bar('bob')
# student.name = 1
# del student.name
print(student.name)

猜你喜欢

转载自blog.csdn.net/ltfdsy/article/details/81950488