Найти - Пользователи
Полная версия: класс(решено)
Начало » Python для новичков » класс(решено)
1
Michail_V
class Nume(object):
    def __init__ (self, numero):
        self.n = numero
    def __add__(self, other):
            if isinstance(other, Nume):
                     return Nume(self.n + other.n)

>>> a = Nume(3)
>>> b = Nume(7)
>>> a+b
<__main__.Nume object at 0x7f51c6a64e10>

оно создаёт ещё 1 объект класса Nume, который равен a+b

>>> c = a + b
>>> c
<__main__.Nume object at 0x7f51c6a64e50>


как сделать так, чтобы когда я спрашивал “с”, мне выдавало в ответ “10”????


PS: да это класс с простыми числами просто тренируюсь, чтобы всё правильно понимать

Singularity
>>> class Nume(object):
	def __str__(self):
		return "Str",self.n
	def __repr__(self):
		return "Repr",self.n
	def __init__(self,numero):
		self.n = numero
	def __add__(self, other):
		if isinstance(other, Nume):
			return Nume(self.n + other.n)
		
>>> 
>>> a = Nume(3)
>>> b = Nume(7)
>>> a+b
Repr 10
>>> print a+b
Str 10
>>> 
Singularity
Кстати надо подсвечивать код на форуме по ссылке ниже vvvv
Michail_V
спс а где можно на русском почитать о всех встроенных протоколах классов? (таких как __str__ и др.)
Singularity
На русском вот
http://www.ibm.com/developerworks/ru/library/l-python_part_7/

Советую учиться гуглить самостоятельно
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB