w*s 发帖数: 7227 | 1 in c code i can do this
func(struct aaa *)
{
aaa->f1 = 1;
aaa->f2 = "abc";
}
how to do this in python pls ? |
d**o 发帖数: 864 | 2 create a class aaa
if you give an instance of aaa as a parameter to a function, the reference
is passed.
You don't need to do anything special.
class aaa:
def __init__(self):
self.a=1
def treat(aaa):
aaa.a=2
ins=aaa()
print ins.a
treat(ins)
print ins.a
【在 w*s 的大作中提到】 : in c code i can do this : func(struct aaa *) : { : aaa->f1 = 1; : aaa->f2 = "abc"; : } : how to do this in python pls ?
|
w*s 发帖数: 7227 | 3 good to know.
any limitations that c++ can do, but python cannot,
for structure, passing buffer, passing by reference ?
thx !
【在 d**o 的大作中提到】 : create a class aaa : if you give an instance of aaa as a parameter to a function, the reference : is passed. : You don't need to do anything special. : class aaa: : def __init__(self): : self.a=1 : def treat(aaa): : aaa.a=2 : ins=aaa()
|
s*s 发帖数: 100 | 4 agreed. Just remember do not reassign the passed parameter.
def treat_surprise(p_a):
b=aaa()
b.a=3
p_a=b # surprise for a C++ programmer!
treat_surprise(ins)
【在 d**o 的大作中提到】 : create a class aaa : if you give an instance of aaa as a parameter to a function, the reference : is passed. : You don't need to do anything special. : class aaa: : def __init__(self): : self.a=1 : def treat(aaa): : aaa.a=2 : ins=aaa()
|
f*******n 发帖数: 12623 | 5 Why is it a surprise? It's the same in C++:
void treat_surprise(aaa *p_a) {
aaa *b = new aaa;
b->a = 3;
p_a = b;
}
【在 s*s 的大作中提到】 : agreed. Just remember do not reassign the passed parameter. : def treat_surprise(p_a): : b=aaa() : b.a=3 : p_a=b # surprise for a C++ programmer! : : treat_surprise(ins)
|
d**o 发帖数: 864 | 6 If you want to copy an object, normally do a copy explicitly.
Cite from Stackoverflow:
"passing by value" and "passing by reference" are not concepts that are
relevant in Python. The relevant concepts are instead "mutable object" and "
immutable object".
【在 w*s 的大作中提到】 : good to know. : any limitations that c++ can do, but python cannot, : for structure, passing buffer, passing by reference ? : thx !
|
s*s 发帖数: 100 | 7 I am thinking this:
void treat_surprise(aaa & p_a) {
.......
.......
}
If you pass by reference, p_a=b will call the copy constructor.
【在 f*******n 的大作中提到】 : Why is it a surprise? It's the same in C++: : void treat_surprise(aaa *p_a) { : aaa *b = new aaa; : b->a = 3; : p_a = b; : }
|
p***o 发帖数: 1252 | 8 Reference in languages like java and python means pointer in C/C++.
【在 s*s 的大作中提到】 : I am thinking this: : void treat_surprise(aaa & p_a) { : ....... : ....... : } : If you pass by reference, p_a=b will call the copy constructor.
|