Actually simple recursion problem on Python [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
During coding I came across with this simple recursion problem and I wrote an example of my code below. I ask somebody to find a good way to solve the problem. I guess it is supposed to write third class containing the relations.
from __future__ import annotations
from typing import Set
class Author:
def __init__(self):
self.books: Set[Book] = set()
def add_book(self, book: Book):
self.books.add(book)
book.add_author(self)
class Book:
def __init__(self):
self.authors: Set[Author] = set()
def add_author(self, author: Author):
self.authors.add(author)
author.add_book(self)
author = Author()
book = Book()
author.add_book(book) #RecursionError: maximum recursion depth exceeded while calling a Python object

The add_book() and add_author() methods call each other, so you get into an infinite loop.
The methods should check whether they're already added and not do anything, this will stop the recursion.
class Author:
def __init__(self):
self.books: Set[Book] = set()
def add_book(self, book: Book):
if book not in self.books:
self.books.add(book)
book.add_author(self)
class Book:
def __init__(self):
self.authors: Set[Author] = set()
def add_author(self, author: Author):
if author not in self.authors:
self.authors.add(author)
author.add_book(self)

Related

How i can rewrite the repeating code from a class function, for better reusability [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 days ago.
The community is reviewing whether to reopen this question as of 5 days ago.
Improve this question
I wrote a class for which I later needed to write a specific logger.
In this particular case, standard Python logging doesn't work for me, for several reasons.
To simplify, it turned out something like this:
class Counter(object):
def __init__(self):
self.foo = 0
self.status = 'Off'
def counter_foo(self, n):
self.foo += n
def set_status(self, status):
self.status = status
def result(self):
print(f'Foo: {self.foo}')
print(self.status)
class First(object):
def __init__(self):
self.counter = Counter()
self.status = 'On'
def print_foo(self, n=1):
# This part is changing
print('foo' * n)
# This part doesn't change.
self.counter.counter_foo(n)
if self.status == 'On':
self.counter.set_status(self.status)
def end(self):
print('Bye!')
self.counter.result()
def main():
foobar = First()
foobar.print_foo(8)
foobar.end()
Part of the code in the First function changes in different projects. But the part about calling the Counter is always the same. In what ways can I redo it for easy transfer from project to project. Is a mixin suitable here, or is it better to make a decorator out of the Counter?
In a real project, in each function of the First class, there may be 3-5 calls to counter functions, but they are always the same.

Dependency injection in __init__ constructor or in method arguments [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 days ago.
Improve this question
I have always been haunted by this question by myself each time I write any classes: Where should I inject the class dependency. Should it be given to __init__ constructor or to the specific method that uses the dependent object..
Take the below 2 pieces of python code for example, to me they function exactly the same way (I might be wrong in saying this, let me know if you have different opinion).
My questions are:
which design is better in this case, and why?
In general, what is the rule to decide if the dependency should be given to the constructor or the specific method?
Any thoughts or references would be really much appreciated!
class TextFile:
def save_text(self, text):
print("Below texts saved to file")
print(text)
class TextWriter:
def __init__(self):
self.text = ""
def write_text(self, text):
self.text += text
def save_text(self, saver): # dependency injected in the specific method
saver.save_text(self.text)
if __name__ == "__main__":
tf_saver = TextFile()
writer = TextWriter()
writer.write_text("Here is some text")
writer.save_text(saver=tf_saver)
class TextFile:
def save_text(self, text):
print("Below texts saved to file")
print(text)
class TextWriter:
def __init__(self, saver): # dependency injected in the constructor
self.text = ""
self.saver = saver
def write_text(self, text):
self.text += text
def save_text(self):
self.saver.save_text(self.text)
if __name__ == "__main__":
tf_saver = TextFile()
writer = TextWriter(tf_saver)
writer.write_text("Here is some text")
writer.save_text()

What is difference between these two codes? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Turtle=Animal("Turtle")
Turtle.set_category("reptile")
and
class Turtle(Animal):
category="reptile"
While learning object composition in python i came across a problem in which latter worked but former did not.
this was the class
class Animal:
name = ""
category = ""
def __init__(self, name):
self.name = name
def set_category(self, category):
self.category = category
These two sequences should behave the same:
turtle=Animal("Turtle")
turtle.set_category("reptile")
and
class Turtle(Animal):
category="reptile"
name = "Turtle"
turtle = Turtle()
The two turtle objects will behave identically.
In the first piece of code you are defining an instance of the Animal class stored in the Turtle variable, whereas in the second piece of code you are defining a new class called Turtle that will inherit from the Animal class.
Read more about class objects here: https://docs.python.org/3/tutorial/classes.html#class-objects
Read more about class inheritance here: https://docs.python.org/3/tutorial/classes.html#inheritance

Why the method in some class I created, ask me for input "self"? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am new in OO programming. It is python 3.
Let be some example code:
class MyClass:
def __init__(self,a=1,b=2):
self.a=a
self.b=b
def function1(self):
c.self=salf.a/self.b + 5
return(c.self)
When I call a method from MyClass. i.e:
MyClass.function1()
it returns:
NameError: name 'self' is not defined.
I understand that if I initialize the code as:
class MyClass(object):
code etc...
It is all right if I put:
somevariable=MyClass; somevariable.function1()
It works... I do not know why this is happening.
Thank you so much !
You have to create an object of your class:
class MyClass:
def __init__(self,a=1,b=2):
self.a=a
self.b=b
def function1(self):
self.c=self.a/self.b + 5
return(self.c)
print(MyClass().function1())
MyClass() creates an object that can be used to access attributes in the class.
For a general instance:
m = MyClass()
print(m.function1())

Python vs Ruby class methods [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
The following two Ruby and Python codes are examples of class methods. Why does python allow accessing class methods through objects but ruby doesn't ?
Python code
class student:
b = 78
#classmethod
def foo(var):
return var.b
z = student()
print z.foo() # => 78
Ruby Code
class Student
##b = 78
def self.foo
##b
end
end
z = Student.new
puts z.foo # => -e:20:in `<main>': undefined method `foo' for #<Student:0x007ff4f98ab9e8> (NoMethodError)
An answer for the ruby side of your question: Ruby does allow accessing class methods through objects via a reader for the class:
class Student
##b = 78
def self.foo
##b
end
end
z = Student.new
puts z.class.foo
z.class returns the class of the object (in this case it is Student).
class Student
end
z = Student.new
puts z.class #Student
puts z.class.class #Class
From Ruby doc Object#display:
display(port=$>)
Prints obj on the given port (default $>). Equivalent to:
def display(port=$>)
port.write self
end
So it just displays the receiver, which is a Student instance. I don't see how this is relevant to class methods.
Calling the class method Student.display is in fact possible:
z.class.display
Ruby doesn't have class methods, only instance methods. In your case, foo is in instance method of the singleton class of Student.
Once you understand that there is no such thing as a class method in Ruby, only instance methods, it should be immediately obvious why calling an instance on a completely different instance cannot possibly work.

Categories