Ask Your Question

Why do I need to use real or real() some of the times?

asked 2019-03-07 18:31:49 +0200

tiger gravatar image

updated 2019-03-08 00:38:46 +0200

I am making my own library to deal with polar to Cartesian conversions and for getting radius and angles in degrees. I use .real and .imag quite a bit and have hit a wall when sometimes it would stop working due to error such as "built-in method real_part of sage.symbolic.expression.Expression" not compatible with method or something like that. This is what I came up with as my solution.

 def getReal(im):
    if type(im)==complex:
        return im.real
    return im.real()
def getImag(im):
    if type(im)==complex:
        return im.imag
    return im.real()

This resolves issue with incompatible expressions

My questions are

  • Why is this necessary?
  • How should I go about making my libraries so that it can be imported into other files without copying over the whole source?
  • How do I create methods such as above that will work on types so I can instead of getReal(i) call i.getReal()?


edit retag flag offensive close merge delete


ps: ("library")

tiger gravatar imagetiger ( 2019-03-08 00:43:11 +0200 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2019-03-08 06:23:39 +0200

nbruin gravatar image

1) The problem is that on a=complex(1), we have that a.real and a.imag are attributes.

On b=CC(1) we have that b.real is a method so you need to call b.real() to get the part. Alternatively, you can use b.real_part().

In sage it's become customary to access data via methods, not via attributes. That's a common tool to make it easy to hide implementation details. Strictly speaking it's not necessary in python because @property allows "getters" and "setters" that can be accessed as if they were attributes.

2) see python modules.

3) The methods available on a certain type of objects are the choice of that object. You don't get to change that. You can subclass, however, and then you can implement whatever methods you like in that subclass.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2019-03-07 18:31:49 +0200

Seen: 208 times

Last updated: Mar 08 '19