属性 (编程) - 维基百科,自由的百科全书

属性(Property),在一些面向对象编程语言中,是的特殊成员,功能上居于字段(或数据成员)与方法之间。可读可写属性的语法类似于字段,但属性的读写操作通常被编译为gettersetter方法调用。属性使用类似于字段的读写语法,比普通的方法调用的语法形式更易于读写操作;但属性读写编译为内部的方法调用,则可以支持数据确认主动修改或实现只读字段等功能。

语言支持

[编辑]

支持属性的编程语言有:ActionScript 3、C#DDelphi/Free PascaleCF#KotlinJavaScriptObjective-C 2.0PythonScalaSwiftLuaVisual Basic

一些面向对象语言,如JavaC++,不支持属性,而要求编程者写一对accessor与mutator方法。 C++可以通过运算符重载来模拟属性。

不同的语法

[编辑]

一些语言用点表示,另一些语言用方括号表示,来访问属性。

点表示法

[编辑]

如JavaScript:

document.createElement('pre'); 

方括号表示法

[编辑]

JavaScript也可以用方括号来访问属性:

document['createElement']('pre'); 

具体语言实现舉例

[编辑]

C#

[编辑]
class Pen  {     private int color; // private field          // public property     public int Color      {           get         {             return this.color;         }         set          {             if (value > 0) {                 this.color = value;             }         }     } } 
// accessing: Pen pen = new Pen(); int color_tmp = 0; // ... pen.Color = 17; color_tmp = pen.Color; // ... pen.Color = ~pen.Color; // bitwise complement ...  // another silly example: pen.Color += 1; // a lot clearer than "pen.set_Color(pen.get_Color() + 1)"! 

高版本的C#支持编译器自动实现属性。

class Shape  {          public Int32 Height { get; set; }     public Int32 Width  { get; private set; }      } 

C++

[编辑]

C++有多种方法模拟属性实现。

#include <iostream>  template <typename T> class property {         T value;     public:         T & operator = (const T &i) {             return value = i;         }         // This template class member function template serves the purpose to make         // typing more strict. Assignment to this is only possible with exact identical types.         // The reason why it will cause an error is temporary variable created while implicit type conversion in reference initialization.         template <typename T2> T2 & operator = (const T2 &i) {             T2 &guard = value;             throw guard; // Never reached.         }          // Implicit conversion back to T.          operator T const & () const {             return value;         } };  struct Foo {     // Properties using unnamed classes.     class {             int value;         public:             int & operator = (const int &i) { return value = i; }             operator int () const { return value; }     } alpha;      class {             float value;         public:             float & operator = (const float &f) { return value = f; }             operator float () const { return value; }     } bravo; };  struct Bar {     // Using the property<>-template.     property <bool> alpha;     property <unsigned int> bravo; };  int main () {     Foo foo;     foo.alpha = 5;     foo.bravo = 5.132f;      Bar bar;     bar.alpha = true;     bar.bravo = true; // This line will yield a compile time error                       // due to the guard template member function.     ::std::cout << foo.alpha << ", "                 << foo.bravo << ", "                 << bar.alpha << ", "                 << bar.bravo                 << ::std::endl;     return 0; } 

C++, Microsoft & C++Builder的方言语法

[编辑]

例子来自MSDN documentation page页面存档备份,存于互联网档案馆):

// declspec_property.cpp struct S {    int i;    void putprop(int j)    {        i = j;    }     int getprop()    {       return i;    }     __declspec(property(get = getprop, put = putprop)) int the_prop; };  int main() {    S s;    s.the_prop = 5;    return s.the_prop; } 

JavaScript

[编辑]
function Pen() {     this._color = 0; } // Add the property to the Pen type itself, can also // be set on the instance individually Object.defineProperties(Pen.prototype, {     color: {         get: function () {             return this._color;         },         set: function (value) {             this._color = value;         }     } }); 
var pen = new Pen(); pen.color = ~pen.color; // bitwise complement pen.color += 1; // Add one 

Python

[编辑]

Python 2.2开始的new-style classes (即派生自object的类)支持属性。见the relevant section of the tutorial Unifying types and classes in Python 2.2页面存档备份,存于互联网档案馆)。Python 2.6支持了定义属性的装饰器语法。

class Pen:     def __init__(self) -> None:         self._color = 0  # "private" variable      @property     def color(self):         return self._color      @color.setter     def color(self, color):         self._color = color 
pen = Pen() # Accessing: pen.color = ~pen.color  # Bitwise complement ... 

参见

[编辑]