Java教程

描述符应用

本文主要是介绍描述符应用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
'''描述符应用'''
# class Typed:
#  def __set__(self, instance, value):
#     print('set方法执行')
#     print('instance参数%s' % instance)
#     print('value参数%s' % value)
#
#  def __get__(self, instance, owner):
#     print('get方法执行')
#     print('instance参数%s' % instance)
#     print('owner参数%s' % owner)
#
#  def __delete__(self, instance):
#     print('delete方法执行')
#     print('instance参数%s' % instance)
#
# class People:
#  name = Typed()
#  def __init__(self, name, age, salary):
#     self.name = name
#     self.age = age
#     self.salary = salary
#
# p1 = People('alex', 18, 10000.55)
# p1.name
# p1.name = 'lhf'
# print(p1.__dict__)


# 类实例化所传入参数加上字符类型限制
class Typed_1:
   def __init__(self, key, expected_type): # ①这里先定义一个__init__,以便作为instance实例属性字典的key值
      self.key = key
      self.expected_type = expected_type

   def __set__(self, instance, value):
      if type(value) == self.expected_type:
         instance.__dict__[self.key] = value # ③这里通过self.key作为instance实例属性字典key值
      else:
         raise TypeError('输入类型错误')

   def __get__(self, instance, owner):
      return instance.__dict__[self.key]

   def __delete__(self, instance):
      instance.__dict__.pop(self.key)

class People_1:
   name = Typed_1('name', str) # ②这里需要传入两个值给__init__
   age = Typed_1('age', int)
   salary = Typed_1('salary', float)
   def __init__(self, name, age, salary):
      self.name = name
      self.age = age
      self.salary = salary

p2 = People_1('小明', 18, 300.33)
# p3 = People_1(999, 18, 300.33)
# p4 = People_1('小红', '18', 300.33)
# p5 = People_1('小亮', 18, 300)
这篇关于描述符应用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!