python高级编程(一)

  1. @property添加属性和自定义属性
    我们可以使用@property装饰器来创建只读属性,@property装饰器会将方法转换为相同名称的只读属性,可以与所定义的属性配合使用,这样可以防止属性被修改。
  • 修饰方法,是方法可以像属性一样访问。
class DataSet(object):
  @property
  def method_with_property(self): ##含有@property
      return 15
  def method_without_property(self): ##不含@property
      return 15

l = DataSet()
print(l.method_with_property) # 加了@property后,可以用调用属性的形式来调用方法,后面不需要加()。
print(l.method_without_property())  #没有加@property , 必须使用正常的调用方法的形式,即在后面加()
  • 与所定义的属性配合使用,这样可以防止属性被修改。
class DataSet(object):
    def __init__(self):
        self._images = 1
        self._labels = 2 #定义属性的名称
    @property
    def images(self): #方法加入@property后,这个方法相当于一个属性,这个属性可以让用户进行使用,而且用户有没办法随意修改。
        return self._images 
    @property
    def labels(self):
        return self._labels
l = DataSet()
#用户进行属性调用的时候,直接调用images即可,而不用知道属性名_images,因此用户无法更改属性,从而保护了类的属性。
print(l.images) # 加了@property后,可以用调用属性的形式来调用方法,后面不需要加()。
  • 使用property定义setter函数
class Student:
    @property
    def score(self):
        return self._score  

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('not int')

        elif (value < 0) or (value > 100):
            raise ValueError('not between 0 ~ 100')

        self._score = value

s = Student()
s.score = 75
print(s.score)
# 函数用property修饰后,会返回一个与函数名一样的对象,
#通过@对象.setter修饰另一个函数,可以将该函数转换为setter方法
  1. slots()函数
    python是一门动态语言,可以在类的外面自定义添加属性方法。为了避免用户随意添加,slots()对可以添加的属性方法名称做了一些限定。
from types import MethodType

class MyClass(object):
    __slots__ = ['name', 'set_name'] # 设置只能添加的属性方法的名称

def set_name(self, name):
    self.name = name

cls = MyClass()
cls.name = 'Tom'
cls.set_name = MethodType(set_name, cls) #为某个对象添加一个函数
ls.set_name('Jerry')
print(cls.name)

注:slots仅对当前类实例起作用,对继承的子类是不起作用的。

(;´д`)ゞ写的好累 ,之后再慢慢更新吧

【参考文献】:

(文章内容来源于网络,侵删。)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。