Property (programming)

Property (programming)

In some object-oriented programming languages, a property is a special sort of class member, intermediate between a field (or data member) and a method. You read and write a property just as you read and write a field, but this is (usually) translated to get and set method calls. The field-like syntax is easier to read and write than lots of method calls, yet the interposition of method calls allows for data validation, active updating (as of GUI visuals), and/or read-only 'fields'. That is, properties are intermediate between member code (methods) and member data (instance variables) of the class, and properties provide a higher level of encapsulation than public fields.

Support in languages

Programming languages that support properties include Delphi/Free Pascal, Visual Basic, C#, D, eC, Objective C 2.0, Python and Vala. Some object-oriented languages, such as C++ and Java, don't support properties, and require the programmer to define a pair of "accessor" and "mutator" methods instead.

In most languages, properties are implemented as a pair of accessor/mutator methods, but accessed using the same syntax as for public fields. Omitting a method from the pair yields a "read-only" or "write-only" property, the latter being rather uncommon.

In some languages with no built-in support for properties, a similar construct can be implemented as a single method that either returns or changes the underlying data, depending on the context of its invocation. Such techniques are used e.g. in Perl.

Example syntax

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_Colorend;

procedure TPen.Set_Color(RHS: Integer);begin m_Color := RHSend;

// accessing:var pen: TPen;// ...pen.Color := not pen.Color;

(*Delphi also supports a 'direct field' syntax -

property Color: 'Integer read m_Color write Set_Color;

or

property Color: Integer read Get_Color write m_Color;

where the compiler generates the exact same code as for reading and writinga field. This offers the efficiency of a field, with the safety of a property.(You can't get a pointer to the property, and you can always replace the memberaccess with a method call.)
*)

Visual Basic 6

' in a class named clsPenPrivate m_Color As Long

Public Property Get Color() As Long Color = m_ColorEnd Property

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

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

Visual Basic

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)"!

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 assignmentint theColor = (pen.color = 0xFF0000);

Python

Properties only work correctly for new-style classes (classes which has object as an ancestor), and are only available in Python 2.2 and newer (see [http://www.python.org/download/releases/2.2/descrintro/#property the relevant secion of the tutorial Unifying types and classes in Python 2.2] ).

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" # __writeonly 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;

eC

class Pen { Color color; public property Color color { get { return color; } set { color = value; } } } // Example Usage Pen pen { red }; Pen pen { color = red }; pen.color = ~pen.color; pen.color += 10; pen.color.r = 255; pen.color = 0xFF0000; pen.color = { 255, 0, 0 }; pen.color = ColorHSV { 0, 100, 100 }; pen.color = ColorLab { 53, 79, 66 }; pen.color = ColorCMYK { 0, 100, 100, 0 };

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 UsagePen *pen = [Pen new] ;pen.color = [NSColor blackColor] ;float red = pen.color.redComponent; [pen.color drawSwatchInRect:NSMakeRect(0, 0, 100, 100)] ;

See also

*Uniform access principle
*Method (computer science)
*Mutator method
*Field (computer science)


Wikimedia Foundation. 2010.

Игры ⚽ Нужен реферат?

Look at other dictionaries:

  • Property (disambiguation) — In law and political theory, property refers to an ownership interest in land or other resources.A property of an object is some intrinsic or extrinsic quality of that object, where the nature of the object in question will depend on the field,… …   Wikipedia

  • Programming Complexity — Programming Complexity, which is often also referred to as Software Complexity is a term that encompasses numerous properties of a piece of software, all of which affect internal interactions. According to several commentators, including… …   Wikipedia

  • Property list — Infobox file format name = Property List extension = .plist mime = owner = Apple Computer and GNUstep, formerly NeXT creatorcode = genre = Serialization of dictionary objects. containerfor = containedby = extendedfrom = extendedto = In the Mac OS …   Wikipedia

  • Property List — Vorlage:Infobox Dateiformat/Wartung/MagischeZahl fehltVorlage:Infobox Dateiformat/Wartung/Standard fehltVorlage:Infobox Dateiformat/Wartung/Website fehlt Property List Dateiendung: .plist MIME Type: application/x plist …   Deutsch Wikipedia

  • Comparison of programming languages — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations …   Wikipedia

  • Comparison of programming languages (object-oriented programming) — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations …   Wikipedia

  • Comparison of programming languages (mapping) — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations …   Wikipedia

  • Constructor (object-oriented programming) — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations …   Wikipedia

  • Object-oriented programming — Programming paradigms Agent oriented Automata based Component based Flow based Pipelined Concatenative Concurrent computing …   Wikipedia

  • Oxygene (programming language) — Oxygene Developer RemObjects Software Stable release 3.0.21 (August 29, 2009; 2 years ago (2009 08 29)) Influenced by Object Pas …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”