Python3入门(九)——面向对象OOP高级编程

一、使用__slots__限制属性绑定

  动态绑定实例的方法:

class Person(object):

    def run(self):
        print("奔跑吧!")


p1 = Person()
p1.name = "江北"

  但是这样,"new出来"的实例就可以为所欲为的绑定任意属性了。

  Python中提供了__solts__来限制属性绑定,这样就只能动态绑定指定的属性了!

class Person(object):
    __slots__ = ("name", "age")

    def run(self):
        print("奔跑吧!")


p1 = Person()
p1.name = "江北"

  // 更多详细限制,不在此处赘述

二、使用@property

  上一章已经讲到,定义的属性可以通过get set来限制,但是似乎不像Java的IDEA一样,可以直接快捷生成对应get set,Python的手写set get显然不符合Python简洁的特性,为此,Python引入了@property(通过前面知道是一个装饰器)来完成这个功能。

  不使用装饰器之前:

class Person(object):

    def get_age(self):
        return self._age

    def set_age(self, age):
        if age > 0:
            self._age = age


p1 = Person()
p1.set_age(18)
print(p1.get_age())

  使用之后:

class Person(object):
    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, age):
        if age > 0:
            self._age = age

# 实际使用p1.age = xx时转为使用set,实际使用p1.age时转为get
p1 = Person()
p1.age = 19
print(p1.age)

  完整示例,参考:https://blog.csdn.net/u013205877/article/details/77804137

  

猜你喜欢

转载自www.cnblogs.com/jiangbei/p/8933593.html