Share to: share facebook share twitter share wa share telegram print page

Propriété (informatique)

Le champ de la propriété peut selon le langage se traduire par un attribut, éventuellement homonyme des accesseurs (getter ou setter).

Utilisation des propriétés

L'usage courant des propriétés est de pouvoir rajouter des instructions appliquées systématiquement au moment de la modification ou de la lecture de toute instance d'une classe sans pour autant modifier l'interface de cette classe.

Les propriétés sont également utilisées pour contrôler l’accès au champ, en rendant celui-ci private pour forcer l'usage aux accesseurs, dans lesquels des contrôles de cohérence peuvent être insérés.

Cette faculté permissive est cependant source de risques, notamment du fait qu'elle permet de modifier les valeurs d'attribut(s) lors d'opération vouée normalement à leur lecture.

Exemples de syntaxe

C et dérivés

Propriétés en 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)"!

Les dernières versions de C# autorisent de plus les "auto-implemented properties", pour lesquelles le champ sous-jacent à la propriété est généré par le compilateur à la compilation. Ceci implique que la propriété ait un 'setter', éventuellement privé.

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

Propriétés en C++

C++ n'a pas de propriétés de classe, mais il existe plusieurs manières d'imiter les propriétés dans une certaine limite. Voici deux exemples :

#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;
}

Propriétés en C++, Microsoft & C++Builder-specific

Un exemple tiré de la 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;
}

Propriétés en 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 alloc] init];
pen.color = [NSColor blackColor];
float red = pen.color.redComponent;
[pen.color drawSwatchInRect:NSMakeRect(0, 0, 100, 100)];

Notez que le moderne Objective-C runtime peut convertir les variables d'instance en propriétés, d'où la déclaration explicite des variables d'instance qui n'est pas nécessaire, mais toujours possible.

Nouveaux langages

Propriétés en langage 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);

Dans D version 2, chaque accesseur de propriété doit être marqué avec @property:

class Pen
{
    private int m_color; // private field
    
    // public get property
    @property public int color () {
        return m_color;
    }
    
    // public set property
    @property public int color (int value) {
        return m_color = value;
    }
}

Propriétés en 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;

(*
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 writing
a 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 member
access with a method call.)
*)

Propriétés en 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

Propriétés en JavaScript ES2015[1]

class Pen() {
    constructor() {
        this._color = 0;
    }

    get color() {
        return this._color;
    }

    set color(value) {
        this._color = value;
    }
}

Propriétés en JavaScript ES5

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

Propriétés en PHP

class Pen {
    private $_color;

    function __set($property, $value) {
        if ($property == 'Color') { 
            return $this->_color = $value;
        }
    }

    function __get($property) {
        if ($property == 'Color') {
            return $this->_color;
        }
    }
}
$p = new Pen();
$p->Color = ~$p->Color; // bitwise complement
echo $p->Color;

Propriétés en Python

Les propriétés ne fonctionnent correctement que pour les nouveaux types de classe qui sont uniquement disponibles en Python 2.2 ou plus récents. Python 2.6 ajoute une nouvelle syntaxe pour définir les propriétés.

class Pen(object):
    def __init__(self):
        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 ...

Propriétés en Ruby

class Pen
    def initialize
        @color = 0
    end
    # there is actually a shortcut for these: attr_accessor :color will
    # synthetise both methods automatically, it was expanded for
    # compatibility with properties actually worth writing out
    def color
        @color
    end
    def color = value
        @color = value
    end
end

pen = Pen.new
pen.color = ~pen.color

Langages Visual Basic

Propriétés en Visual Basic (.NET to 2010)

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

Propriétés en 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

Voir aussi

Notes et références

  1. (en) « ECMAScript 2015 Language Specification », sur ecma-international.org (consulté le ).
Read more information:

Södertäljevägen (E4/E20) är en av Stockholms huvudtrafikpulsådror. Stockholms geografiska läge på några öar mellan Mälaren och Östersjön har varit en bra plats när transporter av människor och gods huvudsakligen gick på vattnet. För transporter till lands var alla vattendrag ett besvärligt hinder och på medeltiden fanns bara några få färdvägar mot söder respektive norr. Ända fram till 1670-talet var Göta landsväg den enda vägförbindelsen söderut mot Götaland. Med Sv…

هوفارد فلو معلومات شخصية الميلاد 4 أبريل 1970 (العمر 53 سنة) الطول 1.87 م (6 قدم 1 1⁄2 بوصة) مركز اللعب مهاجم الجنسية النرويج  أبناء فريدريك فلو  مسيرة الشباب سنوات فريق 1980 Stryn TIL [الإنجليزية]‏ المسيرة الاحترافية1 سنوات فريق م. (هـ.) 1990–1994 سوغندال لكرة القدم 81 (20) 199…

Madalyn Murray O'HairO'Hair pada 1983LahirMadalyn Mays(1919-04-13)13 April 1919Pittsburgh, Pennsylvania, ASMeninggal29 September 1995(1995-09-29) (umur 76)San Antonio, Texas, ASSebab meninggalPembunuhanKebangsaanAmerika SerikatAlmamaterAshland UniversitySouth Texas College of LawPekerjaanAktivis, pendiri dan presiden American AtheistsDikenal atasAbington School District v. Schempp (kasus Mahkamah Agung)Suami/istriJohn Henry Roths ​ ​(m. 1941; bercerai&#…

Universitas Teknologi PetronasUniversiti Teknologi PetronasMotoEngineering FuturesJenisUniversitas swastaDidirikan10 Januari 1997KanselirYABhg Tun Dr Mahathir bin MohamadRektorYBhg Datuk Dr. Zainal Abidin Haji KasimPro-KanselorDato' Shamsul Azhar AbbasJumlah mahasiswaSekurang-kurangnya 6000 sarjana dan sebilangan kecil pascasarjanaLokasiSeri Iskandar, Perak, MalaysiaNama julukanUTPAfiliasiASAIHLSitus webwww.utp.edu.my Universitas Teknologi Petronas (singkatan: UTP) adalah sebuah universitas swas…

Este artículo o sección necesita referencias que aparezcan en una publicación acreditada.Este aviso fue puesto el 30 de diciembre de 2019. Primera División 2017-18 XXVI Primera DivisiónDatos generalesSede Macedonia del NorteAsociación UEFAFecha 12 de agosto de 2017 20 de mayo de 2018Edición 26.ªPalmarésPrimero ShkëndijaSegundo VardarTercero RabotničkiDatos estadísticosParticipantes 10 equiposPartidos 180Goles 461 (2.56 goles por partido)Goleador Ferhan Hasani (22) Besart Ibraimi (22)…

Canadian government executive Minister of Emergency PreparednessMinistre de la Protection civileIncumbentHarjit Sajjansince July 26, 2023Public Safety CanadaStyleThe HonourableMember ofHouse of CommonsPrivy CouncilCabinet[1]Reports toParliamentPrime Minister[2]AppointerMonarch (represented by the governor general);[3]on the advice of the prime minister[4]Term lengthAt His Majesty's pleasureFormation26 October 2021SalaryCA$269,800 (2019)[5]Websitewww.p…

Ibu ArmeniaIbu ArmeniaLetakTaman Kemenangan, Yerevan, ArmeniaKoordinatKoordinat: 40°11′42.90″N 44°31′29.34″E / 40.1952500°N 44.5248167°E / 40.1952500; 44.5248167Ketinggian51 meter (167.3 kaki)Dibangun1967ArsitekRafayel IsrayelianPemahatAra HarutyunyanBadan pengelolaMenteri Pertahanan ArmeniaLokasi Ibu Armenia di Armenia Ibu Armenia (bahasa Armenia: Մայր Հայաստան) adalah personifikasi wanita dari Armenia. Render visualnya yang paling umum adalah…

Ethnic group in Zimbabwe This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: White Zimbabweans – news · newspapers · books · scholar · JSTOR (March 2023) (Learn h…

1080i adalah istilah singkatan untuk satu kategori modus video. Angka 1080 adalah singkatan dari 1080 garis resolusi vertikal, sementara huruf i berarti scan selang seling (interlace) atau bukan progresif. 1080i adalah satu modus video televisi definisi tinggi (HDTV). Istilah ini biasanya merujuk pada rasio aspek layar lebar 16:9, menandakan resolusi horizontal 1920 piksel dan resolusi gambar 1920 × 1080 atau sekitar 2.07 juta piksel. Ukuran bidang dalam satuan hertz dapat ditunjukkan oleh kont…

Garasi IIAlbum studio karya GarasiDirilis16 Agustus 2008GenreAlternative Rock, Big Beat, Alternative DanceLabelTrinity Optima Production Miles MusicKronologi Garasi OST Garasi(2006)OST Garasi2006 Garasi II (2008) Kembali(2011)Kembali2011 Garasi II adalah album kedua grup musik Garasi. Berbeda dengan album pertamanya, album kedua ini tidak dirilis dengan film. Masih di bawah label Miles Music album ini berisi 10 lagu dan 1 bonus track. Lagu andalan dalam album ini adalah Tak Ada Lagi. Ini ada…

Skadron Udara 1/Elang KhatulistiwaLanud SupadioLambang Skadud 1Dibentuk29 April 1950NegaraIndonesiaCabang TNI Angkatan UdaraTipe unitKomando TempurBagian dariWing Udara 7MarkasLanud Supadio, Kubu RayaMotoAkasa Waskita Dwi Matra VidyaUlang tahun29 AprilSitus webwww.tni-au.mil.id Skadron Udara 1/Elang Khatulistiwa adalah sebuah Skadron udara dari Tentara Nasional Indonesia Angkatan Udara, yang berbasis di Pangkalan Udara Supadio, Kabupaten Kubu Raya. Saat ini skadron ini dilengkapi dengan pesawat …

American college football season This article relies largely or entirely on a single source. Relevant discussion may be found on the talk page. Please help improve this article by introducing citations to additional sources.Find sources: 2001 Rice Owls football team – news · newspapers · books · scholar · JSTOR (October 2012) 2001 Rice Owls footballConferenceWestern Athletic ConferenceRecord8–4 (5–3 WAC)Head coachKen Hatfield (8th season)…

Berkeley Co-op logo, as reproduced on a belt buckle, ca 1970s Consumers' Cooperative of Berkeley, informally known as the Berkeley Co-op, or simply Co-op, was a consumers' cooperative based in Berkeley, California which operated from 1939 to 1988,[1][2] when it collapsed due to internal governance disputes and bankruptcy. During its height, it was the largest cooperative of its kind in North America, with over 100,000 members, and its collapse has provoked intense discussion over…

Companhia da Baía de HudsonHudson's Bay CompanyCompagnie de la Baie d'Hudson Companhia da Baía de HudsonLogo Companhia da Baía de HudsonBrasão de armas da Companhia da Baía de Hudson. Tipo Pública[1] Fundação 2 de maio de 1670 Sede Simpson Tower, Toronto, Ontário Proprietário(s) NRDC Equity Partners Presidente Liz Rodbell Pessoas-chave Richard A. Baker, Governador e CEOBonnie Brooks, Vice Chairman[2] Divisões The BayLord & TaylorHome Outfitters Lucro $7.0 biliões CAD Website ofic…

Toberín Vista hacia el suroccidente desde el puente peatonal. UbicaciónCoordenadas 4°44′50″N 74°02′50″O / 4.747107, -74.047104Dirección Av.Carrera 45 con Calle 166Barrio EsteEl ToberínOesteBritaliaLocalidad EsteUsaquénOesteSubaCiudad BogotáDatos de la estaciónNombre anterior ToberínCódigo TM0028Inauguración 6 de agosto de 2001Servicios Propietario TransMilenioOperador SI 18 Norte S.A.S.LíneasLínea(s) AutoNorte « Portal del Norte ← B → Calle 161 » […

AertembagaKecamatanPeta lokasi Kecamatan AertembagaNegara IndonesiaProvinsiSulawesi UtaraKotaBitungKode Kemendagri71.72.04 Kode BPS7172030 Desa/kelurahan10 Selat Lembeh dilihat dari Aertembaga Aertembaga adalah sebuah kecamatan yang terletak di Kota Bitung, Sulawesi Utara, Indonesia. Sebelum tahun 2007, nama Kecamatan Aertembaga adalah Kecamatan Bitung Timur. Sebagian wilayah Kecamatan Aertembaga telah dimekarkan untuk membentuk Kecamatan Madidir. Wilayah Kecamatan Aertembaga berada di data…

2018年國際足協女子U-20世界盃2018 FIFA U-20 Women's World Cup賽事資料屆數第9屆主辦國法國比賽日期8月5日–8月24日參賽隊數16 隊(來自6個大洲)球場4個(位於4個城市)衛冕球隊 朝鲜最終成績冠軍 日本(第1次奪冠)亞軍 西班牙季軍 英格兰殿軍 法國賽事統計比賽場數32場總入球數98球(場均3.06球)入場人數75,748人(場均2,367人)← 2016 2020 → 2018年國際足協女子U-20世界盃是第 9 屆國…

River in northern Powys, Wales Afon Tanat near Llangedwyn Afon Tanat is a river in northern Powys, Wales. Its source is close to the Cyrniau Nod mountain, to the north of Lake Vyrnwy. The river flows in a generally east-south-east direction until it joins the River Vyrnwy near Llansantffraid-ym-Mechain. For a short distance prior to its confluence it flows within western Shropshire, England.[1] Its tributaries include the Afon Eirth, Afon Rhaeadr, Afon Iwrch and Afon Goch.[2] Ref…

2002 American filmTabooDirected byMax MakowskiWritten byChris FisherProduced byChris FisherAsh R. ShahStarringEddie Kaye ThomasNick StahlJanuary JonesAmber BensonDerek HamiltonLori HeuringCinematographyViorel Sergovici Jr.Edited byM. Scott SmithMusic byRyan BeveridgeProductioncompaniesCreative Entertainment GroupImperial Fish CompanySilver BulletRelease dateJanuary 14, 2002Running time80 minutesCountryUnited StatesLanguageEnglish Taboo is an American mystery thriller film directed by Max Makowsk…

School in North Carolina, United States This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Grimsley High School – news · newspapers · books · scholar · JSTOR (September 2012) (Learn how and when to remove this template message) Grimsley Senior High SchoolGrimsley Senior High School, September 2012Address801 North …

Kembali kehalaman sebelumnya

Lokasi Pengunjung: 44.204.99.5