Here, slowly, I am glad to be a python. Background 0, if that.

I want to understand if I did the right thing. There are two classes: rope and knife. There is one object of each class. The rope has a length, the knife is able to cut the rope. Did I understand correctly the essence of using the method of one class that changes the attribute of another? Or is it a children's code curve? thanks for the advice

class Rope: length = 30 def get_info(self): print("\n", "---"*8, "\n", "class Rope, get_info(): ", "\n", "Rope's length is %s meters" % self.length, "\n", "---"*8, "\n" ) class Knife: def cut_rope(self, length, a): print("Now we will cut %s meters off" % length) a.length -= length rope = Rope() knife = Knife() rope.get_info() knife.cut_rope(12, rope) rope.get_info() C:\Users\олег\Python34\classes>ex2.py ------------------------ class Rope, get_info(): Rope's length is 30 meters ------------------------ Now we will cut 12 meters off ------------------------ class Rope, get_info(): Rope's length is 18 meters 
  • Probably better at the rope to make the method cut - Vladimir Gamalyan
  • Does a rope cut itself in the real world? it has methods, say, to tie into a knot (with the help of the object "hand" or "person"). and the knife can have a cut off method - Oleg
  • I am for making the rope immutable - like a string. The cut rope is two new ropes. - Nick Volynkin
  • And then in one thread the rope will be cut, in the other they will increase ... - Nick Volynkin
  • As for the rope.get_info() - the rope introspection method should not be either) - Nick Volynkin

2 answers 2

As already wrote in the commentary, I propose to make the rope an immutable object. And maximize the use of built-in methods.

 # coding=utf-8 class Rope: # зачем хардкодить длину верёвки? Лучше будем задавать её в конструкторе. def __init__(self, length): if length <= 0: raise ValueError('length should be > 0') self._length = length # сработает с методом len() def __len__(self): return self._length # а это сработает с str(), соответственно и с print def __str__(self): return "This rope's length is {0!s} meters".format(self._length) class Knife: # Полиморфизм! Ножу всё равно, что резать. На выходе должно быть два того же. # Если нарезаемое нельзя инициировать только по длине, задаваемой числом, будет ошибка. def cut(self, object, length): _class = object.__class__ # по-хорошему, тут ещё должны быть проверки, что length не None и что число # и, конечно, что object не None if len(object) < length: raise ValueError('cut length exceeds available length') elif len(object) == length: # даже для одного объекта мы возвращаем список, чтобы всегда был перечислимый (iterable) результат return [_class(len(object))] else: return [_class(len(object) - length), _class(length)] rope = Rope(30) knife = Knife() print rope for r in knife.cut(rope, 20): print r 

Conclusion:

 This rope's length is 30 meters This rope's length is 10 meters This rope's length is 20 meters 
  • one
    @VladimirGamalian yeah, I forgot to format it. Now it seems like true polymorphism. )) - Nick Volynkin
  • thank you gentlemen - Oleg
  • One wants to pull the cut method out of the class, and leave it just a "free" function. Although, of course, the example was originally a toy, and the condition of the knife is indispensable) - insolor
  • possible, for str [: slice] - vadim vaduxa
 # -*- coding: UTF-8 -*- class Rope(str): def __init__(self, s: str): self.len = len(self) print("%s rope's length is %s meters" % (self, self.len)) def __getitem__(self, item: slice): return self.__class__(super().__getitem__(item)) class Knife: @staticmethod def cut(string: str, length: int): rope = Rope(string) yield from (rope, rope[:length], rope[length:]) print('{s} cut {}[{}] pos'.format(rope.len, length, s=rope)) if __name__ == '__main__': rope = '-qwertyuiop-' print([(r, r.len) for r in Knife.cut(rope, 5)]) 

out:

 -qwertyuiop- rope's length is 12 meters -qwer rope's length is 5 meters tyuiop- rope's length is 7 meters -qwertyuiop- cut 12[5] pos [('-qwertyuiop-', 12), ('-qwer', 5), ('tyuiop-', 7)] 
  • one
    It is a little strange that the rope is somehow tied to the knife. Moreover, all the ropes, which were cut with a knife, are tied to it. Oo - insolor
  • changed without binding) - vadim vaduxa
  • another question, there is a class forest and forester. the method of planting a tree is the method of a forest or a forester))) - Oleg
  • and what method does your tree plant here ? vadim vaduxa
  • besides, the forest grows just without a forester)))) - vadim vaduxa