[英]Python. Defining a new operation between two built-in types
First of all I have to say that I am quite new to Python and programming in general, so this question may have been asked before, but I just do not know what specific words I should use to look for this. 首先,我不得不说我对Python和编程领域还是很陌生,所以可能以前曾问过这个问题,但我只是不知道应该使用什么具体词来查找。
I am trying to create a module for personal use that operates with rational numbers in a more symbolic way. 我正在尝试创建一个供个人使用的模块,该模块以更具象征意义的方式对有理数进行运算。 I am aware that there are modules to do this, but my objective is not to use the module but to learn by making it.
我知道有一些模块可以做到这一点,但是我的目标不是使用模块而是通过学习来学习它。 My question is whether there is a some way to have Python instatiate a new Rational object when I write a specific operation (ie 2 f 3) instead of having to write Rational(2,3) every time I want to create a new Rational.
我的问题是,当我编写特定的操作(即2 f 3)时,是否有某种方法可以让Python实例化一个新的Rational对象,而不是每次我想创建一个新的Rational时都必须编写Rational(2,3)。 This is the code so far:
到目前为止,这是代码:
class Rational:
"""Contains a rational number and the
information to simplify it and operate."""
def __init__(self, a, b):
if type(a) == int and type(b) == int:
self.num = a
self.den = b
self.simplify()
else:
raise TypeError("Both arguments must be int.")
def __repr__(self):
"""Returns the explicit syntax to create
an object with the same attributes."""
return "Rational({}, {})".format(self.num, self.den)
def __str__(self):
"""Returns the fraction as a/b unless the denominator
is 1, in which case it returns only the numerator."""
if self.den != 1:
return str(self.num) + "/" + str(self.den)
else:
return str(self.num)
def __add__(self, other):
"""Rationals can be added to other rationals, int and float."""
if type(other) == float:
return self.to_float() + other
elif type(other) == int:
s = Rational(self.num + other * self.den, self.den)
return s
elif type(other) == Rational:
s = Rational(
self.num * other.den + other.num * self.den,
self.den * other.den)
s.simplify()
return s
else:
return NotImplemented
def simplify(self):
"""Simplifies the fraction and takes the sign to the numerator."""
# If the num is 0 we don't care about the den.
if self.num == 0:
self.den = 1
else:
# Divide num and den by their gcd.
d = gcd(self.num, self.den)
self.num //= d
self.den //= d
# If the den is negative, move the sign to the num.
if self.den > 0:
pass
else:
self.num = -self.num
self.den = -self.den
def to_float(self):
return float(self.num / self.den)
def gcd(a, b):
"""Returns the gcd of two integers."""
while b:
a, b = b, a % b
return abs(a)
Apart of answering the question, if you have any advice about my code I am more than happy to listen to your feedback and learn :) 除了回答问题之外,如果您对我的代码有任何建议,我非常乐意听取您的反馈并学习:)
No you cannot define new operators in python. 不,您不能在python中定义新的运算符。 You can however override the behavior of existing operators.
但是,您可以覆盖现有运算符的行为。
The python docs have more details: https://docs.python.org/2/reference/datamodel.html python文档具有更多详细信息: https : //docs.python.org/2/reference/datamodel.html
Wow, what you are looking for is impossible, not just in python but almost in every programming language. 哇,您要寻找的是不可能的,不仅是在python中,而且在几乎每种编程语言中都是如此。
Because what you want is defining a new operator, that also means you need a new key word to achieve this. 因为您要定义一个新的运算符,所以这也意味着您需要一个新的关键字来实现此目的。 But the key words list must be fixed as the compiler/interpreter will not also be updated by your code.
但是关键字列表必须固定,因为您的代码也不会更新编译器/解释器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.