python基础特性之函数property

函数property

创新互联是一家专注于网站设计、成都网站设计与策划设计,范县网站建设哪家好?创新互联做网站,专注于网站建设十多年,网设计领域的专业建站公司;建站业务涵盖:范县等地区。范县做网站价格咨询:13518219792

1.为了保护属性,不让它随意的被更改(a.width=xxx)(起码,要符合某些条件),所以我们引入了set和get方法,虽然这个需要自定义(如下图的set_size,get_size方法)。

>>> class Rectangle:

... def __init__(self):

... self.width=0

... self.height=0

... def set_size(self,size):

... self.width,self.height=size

... def get_size(self):

... return self.width,self.height

...

>>> r=Rectangle()

>>> r.width=10

>>> r.height=5

>>> r.get_size()

(10, 5)

>>> r.set_size((150,100))

#注意:

#r.set_size((150,100))即:

#self.width,self.height=(150,100)或150,100 即:

#self.width=150,self.height=100

>>> r.width

150

>>> r.height

100

2.但是这样设置和取得属性值(这里指size的值)太麻烦了,如果要设置和取得多个属性的值,要使用非常多次的set和get方法,所以,这里,我们将set和get方法封装起来,让用户像width和height一样快速赋值和访问。

>>> class Rectangle:

... def __init__(self):

... self.width=0

... self.height=0

... def set_size(self,size):

... self.width,self.height=size

... def get_size(self):

... return self.width,self.height

#使用property函数,将size的get和set方法都封装到size这个变量中

... size=property(get_size,set_size)

...

>>> r=Rectangle()

>>> r.width=10

>>> r.height=5

>>> r.size #快速访问size,取得size的值,无需关心size内部的获取值的函数细节

(10, 5)

>>> r.size=150,100

>>> r.width

150

>>> r.size=(100,50) #快速设置size的值,无需关心size内部的设置值的函数细节

>>> r.width

100

>>> r.height

50

Tips——关于property的参数问题:

class property([get[, set[, del[, doc]]]])

#注:

# 1.get -- 获取属性值的函数

# 2.set -- 设置属性值的函数

# 3.del -- 删除属性值函数

# 4.doc -- 属性描述信息

没有传递任何参数的时候,如:size=property(),则创建的特性size将既不可读也不可写。

只传递一个参数的时候,如:size=property(get_size),则创建的特性size将是只读的。

传递三个参数,即传递set、get和del。

传递四个参数,即传递set、get、del和doc(文档字符串,用于描述属性,直接传入信息的内容string即可)。如:

size = property(get, set, del, "I'm the 'x' property.")

静态方法和类方法郑州人流多少钱 http://mobile.zyyyzz.com/

>>> class MyClass:

... def meth():

... print("This is a common method")

# 创建静态方法

# 方法一:手工替换

... def smeth():

... print("This is a static method")

... smeth=staticmethod(smeth)

# 方法二:使用修饰器

... # @staticmethod

... # def smeth():

... # print("This is a static method")

# 创建类方法

# 方法一:手工替换

... def cmeth(cls):

... print("This is a class method")

... cmeth=classmethod(cmeth)

# 方法二:使用修饰器

... # @classmethod

... # def cmeth(cls):

... # print("This is a class method")

...

#通过类直接访问方法

>>> MyClass.meth()

This is a common method

>>> MyClass.smeth()

This is a static method

>>> MyClass.cmeth()

This is a class method

#通过类实例访问方法

>>> myclass=MyClass()

>>> myclass.meth() #实例myclass会将自身作为一个参数传递给meth方法,而meth方法并没有为它定义参数self,从而导致异常

Traceback (most recent call last):

File "", line 1, in

TypeError: meth() takes 0 positional arguments but 1 was given

>>> myclass.smeth()

This is a static method

>>> myclass.cmeth()

This is a class method


文章标题:python基础特性之函数property
文章位置:http://myzitong.com/article/gcpgos.html