ویژگی (برنامه‌نویسی)

در برخی از زبان‌های شی‌گرا، ویژگی  حالتی از اعضای کلاس است که خصوصیاتی ما بین فیلد و متد دارد. آن‌ها مانند فیلدها قابلیت خواندن و نوشتن دارند ولی خواندن و نوشتن در آن‌ها (معمولا) به فراخوانی یک تابع می‌انجامد.

 پشتیبانی در زبان‌ها 
زبان‌هایی که property را پشتیبانی می‌کند شامل دلفی٬ ویژوال بیسیک سی‌شارپ و بسیاری از زبان‌های شی‌گرا می‌شود ولی بعضی از زبان‌های شی گرا مانند جاوا این قابلیت را به صورت محدودتری دارا هستند.

 مثال 

 Delphi/Free Pascal 
type TPen = class
  private
    m_Color: Integer;
    function Get_Color: Integer;
    procedure Set_Color(RHS: Integer);
  public
    property Color: Integer read Get_Color write Set_Color;
end;

function TPen.Get_Color: Integer;
begin
  Result := m_Color
end;

procedure TPen.Set_Color(RHS: Integer);
begin
  m_Color := RHS
end;
// accessing:
var pen: TPen;
// ...
pen.Color := not pen.Color;

 Visual Basic 6 
' in a class named clsPen
Private m_Color As Long

Public Property Get Color() As Long
    Color = m_Color
End Property

Public Property Let Color(ByVal RHS As Long)
    m_Color = RHS
End Property

' accessing:
Dim pen As New clsPen
' ...
pen.Color = Not pen.Color

 Visual Basic (.NET to 2008) 
Public Class Pen

    Private m_Color As Integer ' Private field

    Public Property Color As Integer ' Public property
        Get
            Return m_Color
        End Get
        Set(ByVal Value As Integer)
            m_Color = Value
        End Set
    End Property

End Class

' accessing:
Dim pen As New Pen()
' ...
pen.Color = Not pen.Color

 C# 
class Pen
{
    private int m_Color; // private field

    public int Color   // public property
    {
        get
        {
            return m_Color;
        }
        set 
        {
            m_Color = value;
        }
    }
}

// accessing:
Pen pen = new Pen();
// ...
pen.Color = ~pen.Color; // bitwise complement ...

// another silly example:
pen.Color += 1; // a lot clearer than "pen.set_Color(pen.get_Color() + 1)"!

در نسخه اخیر آن به صورت ساده‌تری درست شده‌است.

class Shape {

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

}

 C++ 
این قابلیت را به صورت درجه یک دارا نیست ولی با راه‌های مختلفی می‌توان آن‌را شبیه سازی کرد.
#include <iostream>

template <typename T> class property {
        T value;
    public:
        T & operator = (const T &i) {
            ::std::cout << i << ::std::endl;
            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.
        template <typename T2> T2 & operator = (const T2 &i) {
            ::std::cout << "T2: " << i << ::std::endl;
            T2 &guard = value;
            throw guard; // Never reached.
        }
        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 specific 
// 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;
}

 Dev D 
class Pen
{
    private int m_color; // private field

    // public get property
    public int color () {
        return m_color;
    }

    // public set property
    public int color (int value) {
        return m_color = value;
    }
}

auto pen = new Pen;
pen.color = ~pen.color; // bitwise complement

// the set property can also be used in expressions, just like regular assignment
int theColor = (pen.color = 0xFF0000);

 Python 
از پایتون ۲/۲ به بعد پشتیبانی شده‌است.
class Pen(object):
    def __init__(self):
        self.__color = 0 # "private" variable
        self.__writeonly = "You can't read this!"

    def _set_color(self, color):
        self.__color = color

    def _get_color(self):
        return self.__color

    color = property(_get_color, _set_color) # read/write access translates to get/set methods

    def _set_writeonly(self, new_value):
        self.__writeonly = new_value

    writeonly = property(fset = _set_writeonly) # write-only access is provided (reading throws an exception)''

pen = Pen()
# accessing:
pen.color = ~pen.color # bitwise complement ...

print pen.writeonly # raise "AttributeError: unreadable attribute"
pen.writeonly = "Something Else" # <code>__writeonly</code> is now "Something Else"
print pen._Pen__writeonly

 PHP 
class Pen {
    private $_color;

    function __set($property, $value) {
        switch ($property) {
            case 'Color': $this->_color = $value; break;
        }
    }

    function __get($property) {
        switch ($property) {
            case 'Color': return $this->_color; break;
        }
    }
}

$p = new Pen();
$p->Color = !$p->Color;
echo $p->Color;

 F# 
type Pen() = class
    let mutable _color = 0

    member this.Color
        with get() = _color
        and set value = _color <- value
end
let pen = new Pen()
pen.Color <- ~~~pen.Color

 Objective C 2.0 

 @interface Pen : NSObject {
   NSColor *color;
}
@property(copy) NSColor *color;        // color values always copied.
@end

@implementation Pen
@synthesize color;                     // synthesize accessor methods.
@end

// Example Usage
Pen *pen = [Pen new];
pen.color = [NSColor blackColor];
float red = pen.color.redComponent;
[pen.color drawSwatchInRect:NSMakeRect(0, 0, 100, 100)];

 منبع 

رده:برنامه‌نویسی شیءگرا