Add a variable to a class instance at runtime: Difference between revisions

added PowerShell
No edit summary
(added PowerShell)
Line 222:
met1(bar) => ;;; new value
</pre>
 
=={{header|PowerShell}}==
PowerShell allows extending arbitrary object instances at runtime with the <code>Add-Member</code> cmdlet. The following example adds a property ''Title'' to an integer:
<lang powershell>$x = 42 `
| Add-Member -PassThru `
NoteProperty `
Title `
"The answer to the question about life, the universe and everything"</lang>
Now that property can be accessed:
<pre>PS> $x.Title
The answer to the question about life, the universe and everything</pre>
or reflected:
<pre>PS> $x | Get-Member
 
TypeName: System.Int32
 
Name MemberType Definition
---- ---------- ----------
CompareTo Method int CompareTo(System.Object value), ...
Equals Method bool Equals(System.Object obj), bool...
GetHashCode Method int GetHashCode()
GetType Method type GetType()
GetTypeCode Method System.TypeCode GetTypeCode()
ToString Method string ToString(), string ToString(s...
Title NoteProperty System.String Title=The answer to th...</pre>
While trying to access the same property in another instance will fail:
<pre>PS> $y = 42
PS> $y.Title</pre>
(which simply causes no output).
 
=={{header|Python}}==
Anonymous user