Lost1 - 1 year ago 58

Python Question

My apologies if this is a stupid question but

if we have

x=3+5j

then

x.imag would give its imaginary part

x.conjugate() would give its complex conjugate. Why do we need to put a () to call the conjugate function?

I am thinking whether x can be thought to be a struct in C++

imag is a public attribute of x, where conjugate is a member function. Is this way of thinking correct? I apologise if this makes no sense. Admittedly, my knowledge of C++ and Python are both quite limited.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

`x`

is not a `struct`

, it is an `object`

of type `complex`

(although sometimes it helps to think of `object`

s as `struct`

s with methods bound to them).

```
>>> type(x)
<class 'complex'>
>>> x = 3+5j
>>> type(x)
<class 'complex'>
```

`x.imag`

is not a function, it's an `attribute`

of the object `x`

that is a `float`

object. An `attribute`

does not have to be called with the parentheses `()`

in order to retrieve its value. Its value is `5`

in your example. You can test if it's a function by calling `callable`

on it. `float`

objects are not callable.

```
>>> x.imag
5.0
>>> type(x.imag)
<class 'float'>
>>> callable(x.imag)
False
```

`x.conjugate`

*is* a function, since `callable(x.conjucate)`

returns `True`

. You call the function by putting the parentheses `()`

after it with the function parameters inside the parentheses. When called, it returns a new `object`

of type `complex`

, which in turn also has the method `conjugate`

which can be called.

```
>>> x.conjugate
<built-in method conjugate of complex object at 0x00000000034D2C90>
>>> callable(x.conjugate)
True
>>> x.conjugate()
(3-5j)
>>> type(x.conjugate())
<class 'complex'>
>>> x.conjugate().conjugate()
(3+5j)
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**