How to access property or method from a variable?
You can do it, but not using "pure" Swift. The whole point of Swift (as a language) is to prevent that sort of dangerous dynamic property access. You'd have to use Cocoa's Key-Value Coding feature:
self.setValue(value, forKey:field)
Very handy, and it crosses exactly the string-to-property-name bridge that you want to cross, but beware: here be dragons.
(But it would be better, if possible, to reimplement your architecture as a dictionary. A dictionary has arbitrary string keys and corresponding values, and thus there is no bridge to cross.)
Accessing Object property from within another object method
var obj = { x: null, func1: function() { console.log('func1, x is ' + this); },
func2: function() { console.log("func2"); this.func1();
var func1 = this.func1; func3(func1); } };
function func3(callback) { console.log("func3"); return callback(); }
obj.func2();
How to access the function property of a javascript object using variable
Was able to make it work, i am converting everything to string and calling it using eval function:
let test={ a:function(tmp){ document.write(tmp) } } let functn='a("hello")'; eval(Object.keys({test})[0]+'.'+functn)
Accessing an object property with a dynamically-computed name
There are two ways to access properties of an object:
- Dot notation:
something.bar
- Bracket notation:
something['bar']
The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:
var something = {
bar: 'foo'
};
var foo = 'bar';
// both x = something[foo] and something[foo] = x work as expected
console.log(something[foo]);
console.log(something.bar)
How to access field value in property get() method
The magical variable it
exists in lambdas. The magical variable used for accessing the property value is called field
. See the documentation for more information.
var test: String = "string"
get() {
logIt("Property accessed")
return field
}
Set and Get @property method in Python by string variable
Calling getattr(model_class, model_attribute)
will return the property object that model_attribute
refers to. I'm assuming you already know this and are trying to access the value of the property object.
class A(object):
def __init__(self):
self._myprop = "Hello"
@property
def myprop(self):
return self._myprop
@myprop.setter
def myprop(self, v):
self._myprop = v
prop = getattr(A, "myprop")
print prop
# <property object at 0x7fe1b595a2b8>
Now that we have obtained the property object from the class we want to access its value. Properties have three methods fget
, fset
, and fdel
that provide access to the getter
, settter
, and deleter
methods defined for that property.
Since myprop
is an instance method, we'll have to create an instance so we can call it.
print prop.fget
# <function myprop at 0x7fe1b595d5f0>
print prop.fset
# <function myprop at 0x7fe1b595d668>
print prop.fdel # We never defined a deleter method
# None
a = A()
print prop.fget(a)
# Hello
In Kotlin, is it possible to use a variable to call a method or property?
You can either do it at compile time if You can directly reference the fields, or at runtime but you will lose compile-time safety:
// by referencing KProperty directly (compile-time safety, does not require kotlin-reflect.jar)
val myData = MyDataClass("first", 2)
val prop = myData::one
prop.set("second")
// by reflection (executed at runtime - not safe, requires kotlin-reflect.jar)
val myData2 = MyDataClass("first", 2)
val reflectProp = myData::class.memberProperties.find { it.name == "one" }
if(reflectProp is KMutableProperty<*>) {
reflectProp.setter.call(myData2, "second")
}
JavaScript object: access variable property by name as string
You don't need a function for it - simply use the bracket notation:
var side = columns['right'];
This is equal to dot notation, var side = columns.right;
, except the fact that right
could also come from a variable, function return value, etc., when using bracket notation.
If you NEED a function for it, here it is:
function read_prop(obj, prop) {
return obj[prop];
}
To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:
var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};
you can access property x
of c
as follows:
var cx = foo['c']['x']
If a property is undefined, an attempt to reference it will return undefined
(not null
or false
):
foo['c']['q'] === null
// returns false
foo['c']['q'] === false
// returns false
foo['c']['q'] === undefined
// returns true
Related Topics
Cocoa Pods Install on iOS Project Not Working
How to Convert Base64 into Nsdata in Swift
Snapshot of Swiftui View Is Partially Cut Off
How to Set the Size of an Uiviewrepresentable
Avaudioplayer Working on Simulator But Not on Real Device
Swift Do Subclasses Inherit Initializers
Can't Dismiss Navigation Controller in Swift
Swift Save Viewcontroller State Using Coder Beyond App Close
Transfer Gestures on a Uiview to a Uitableview in Swift - iOS
Mysterious "Cryptographic Verification Failure" Error on MACos Sierra, Xcode 8
Uicollectionview Cells with Images Inside Uitableview Prototype
Swift - Update/Refresh Label That Displays Time
iOS Firebase Database Get Key of Value
Swift: Terminating with Uncaught Exception of Type Nsexception
Adding Firebase Data to an Array in iOS Swift