Ask Your Question
1

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

asked 2019-03-07 11:31:49 -0500

tiger gravatar image

updated 2019-03-07 17:38:46 -0500

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()?

Thanks!

edit retag flag offensive close merge delete

Comments

ps: https://gist.github.com/kaovilai/8c5134a433e5288324a1e2708552144f ("library")

tiger gravatar imagetiger ( 2019-03-07 17:43:11 -0500 )edit

1 answer

Sort by ยป oldest newest most voted
0

answered 2019-03-07 23:23:39 -0500

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

Stats

Asked: 2019-03-07 11:31:49 -0500

Seen: 51 times

Last updated: Mar 07