I don't know if this is that easy nobody is looking for that, but I didn't found anything...
I want to do the following:
public class foo
{
string X
{
get;
set
{
//set and do some other stuff
}
}
//some other functions
}
Main:
private foo = new foo();
foo = "bla";
How can I assign this bla
DIRECTLY to the class-variable foo
without using foo.X = "bla"
?
How are the datatypes doing this, e.g string?
How are they made?
Because I can do string y; y = "abc"
?
Use dot notation or setattr() function to set the value of class attribute. Python is a dynamic language. Therefore, you can assign a class variable to a class at runtime. Python stores class variables in the __dict__ attribute.
Assigning values to variables is achieved by the = operator. The = operator has a variable identifier on the left and a value on the right (of any value type). Assigning is done from right to left, so a statement like var sum = 5 + 3; will assign 8 to the variable sum .
The C++ compilers calls a constructor when creating an object. The constructors help to assign values to class members.
Are you looking for implicit operator?
public class foo {
string X {
get;
set;
}
public static implicit operator foo(string value) {
return new foo() {
X = value
};
}
}
Please, notice, that there's no constructor call here which will be called (and thus create a new foo instance) implicitly:
private foo myFoo = "bla";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With