Returning variable vs. Setting variable - python

I'm considering the following approaches for class initialisation:
class Foo():
def __init__(self):
self.name = self.get_name()
def get_name(self):
return raw_input("Name: ")
class Foo():
def __init__(self):
self.name = ""
self.get_name()
def get_name(self):
self.name = raw_input("Name: ")
class Foo():
def __init__(self):
self.name = raw_input("Name: ")
Is there any practical reason to opt for one over the others?
If not, which might be considered most Pythonic?

If possible, input() the name outside of the class and pass it as a parameter to its __init__().
If this is not an option, I would go for the second alternative
I would rename get_name() to something like query_name() or input_name(). get_name() sounds like a getter (that gets the value of name) not like a setter or a routine that gets data from the user.

I don't like the idea of doing a raw input in the constructor, but after all, why not...
I would prefer:
class Foo():
def __init__(self):
self.name = ""
def prompt_name(self):
self.name = raw_input("Name: ")
if __name__ == "__main__":
aFoo = Foo()
aFoo.prompt_name()

Related

How do we call a class without passing variables on the call?

Here is a MRE:
class Dog():
def __init__(self, action, name):
self.action = action
self.name = name
def name_dog(self):
my_name = input("give me a name: ")
return self.name(my_name)
def act_like_dog(self):
order = input("Tell me to do something: ")
msg = self.name + " is " + order
return self.action(msg)
def main(self):
self.name_dog()
self.act_like_dog()
Dog.main()
The main objective for calling the dog class in this case is for the user to input their own values (name, action) for the class. So the variables for the class I specified (Dog class) are obtained from a function call (self.name_dog and self.act_like_dog) in the main() function, which prompts the user to give his/her input. However when I tried calling the main() function without self, I got an error saying a positional argument is needed, while if I called the function self(), an error says that self is not defined. How do I fix this?
You seem to be confused about a few elements.
You need to create an actual instance of the class to be able to class its methods - Dog(...). Apart from that, there is a logical problem where you expect to create an instance with name and action but then take them as inputs from the user. I think what you should do is simply set the attributes with user input in the __init__. Something like:
class Dog():
def __init__(self):
self.name = self.name_dog()
self.action = self.act_like_dog()
def name_dog(self):
my_name = input("give me a name: ")
return my_name
def act_like_dog(self):
order = input("Tell me to do something: ")
msg = self.name + " is " + order
return msg
dog = Dog()
If you want to be able to change the name and action later, you can use your main idea:
class Dog():
def __init__(self):
main()
...
def main():
self.name = self.name_dog()
self.action = self.act_like_dog()
dog = Dog()
You might be looking for something like so:
class Dog:
def __init__(self, action=None, name=None):
if name:
self.name = name
else:
self.name = input("Dog's name: ")
if action:
self.action = action
else:
self.action = input("Dog's action: ")
d = Dog()
# ... or ...
d = Dog("Max", "Bark")
# ... or ...
d = Dog("Max")
d = Dog(name="Max")
# ... or ...
d = Dog(action="Bark")

to change the value of instance variable

I want to print name as tanya but since self.name = None has been assigned in constructor it is printing None. So how to get tanya printed when the check function gets called:
class A:
def __init__(self):
self.name = None
def price(self):
self.name = "tanya"
def check(self):
print(self.price())
a=A()
a.check()
The constructor isn't the problem
print(self.price()) is going to print None because you are printing the result of the function.
It then sets self.name="tanya" after printing, but you are ignoring it
Instead, I think you want
a=A()
a.price()
print(a.name)
and forget the check function
class A:
def __init__(self):
self.name=None
def price(self):
self.name="tanya"
return self.name
def check(self):
print(self.price())
a=A()
a.check()
You just have to add the return statement in the price function, and you're done!

Printing a list from a class in Python

My simplified code is below: it creates an animal, and places it inside a zoo. I want to print the list of animals within the zoo. Going round in circles with this!
class Animal(object):
def __init__(self, name):
self.name = name
class Zoo(object):
def __init__(self):
self.animals = []
def __str__(self):
rep = ", ".join(self.animals)
return rep
def add(self, name):
self.animals.append(Animal(name))
def main():
while True:
zoo = Zoo()
animal = input("add an animal: ")
zoo.add(animal)
print(zoo)
main()
The added __repr__ Method to the Animal returns us the name.
The zoo = Zoo() has to be outside of the loop, this makes sure that we do not create a new zoo with every iteration.
Then we print the list (zoo.animals).
class Animal(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
class Zoo(object):
def __init__(self):
self.animals = []
def __str__(self):
rep = ", ".join(self.animals)
return rep
def add(self, name):
self.animals.append(Animal(name))
def main():
zoo = Zoo()
while True:
animal = input("add an animal: ")
zoo.add(animal)
print(zoo.animals)
main()
You can simply refer to the name property of Animal in your Zoo.__str__(), e.g.:
def __str__(self):
return ', '.join(animal.name for animal in self.animals)
Now print(zoo) should work correctly.
However this doesn't provide a lot of encapsulation if say you wanted to change what it means to print an animal, e.g. height, size, etc. So perhaps a more encapsulated form would be:
class Animal(object):
...
def __str__(self):
return self.name
class Zoo(object):
...
def __str__(self):
return ", ".join(str(animal) for animal in self.animals)
Now when you print(zoo) the Animal class is responsible for its own string presentation.
Just as a note: you probably should create the Animal instance outside of Zoo, what happens if you decide to create a class hierarchy of Animals (e.g. Mammal) that has different behaviours, your Zoo class would only know about Animals.
class Animal(object):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class Zoo(object):
def __init__(self):
self.animals = []
def __str__(self):
return ", ".join(str(animal) for animal in self.animals)
def add(self, animal):
self.animals.append(animal)
def main():
zoo = Zoo()
while True:
animal = Animal(input("add an animal: "))
zoo.add(animal)
print(zoo)
main()
This would still behave properly if you create a Mammal class:
class Mammal(Animal):
...
zoo.add(Mammal(...))
print(zoo)

Python - Class methods with input

How can I create a method in a class with a user input?
What argument should I pass when I am calling the method ?
class Student:
def __init__(self):
self._name = ''
def getName(self):
return self._name
def setName(self, newName):
newName = input ('Inserire nome:')
self._name = newName
studente = Student()
studente.setName(newName)
This should work:
class Student:
def __init__(self):
self._name = ''
def getName(self):
return self._name
def setName(self, newName):
self._name = newName
studente = Student()
newName = input('Inserire nome:')
studente.setName(newName)
You were defining the input inside the method itself but passing the variable outside. So the variable newName wasn't defined outside. Let me know if it doesn't work. I haven't tested it, but seems like the conspicuous error here.
If I understood what you want correctly,
why dont you try to ask for an input when initialsing class instance?
class MyClass(object):
def __init__(self):
self.name = input('Enter name> ')
X = MyClass() # when executing that line, you'll be asked for a name to input
Then you'll be able to acces name attribute by X.name and set it to whatever you'd like to by X.name = foo
You could also play with the builtin setattr and dismiss the explicit setters/getters:
class Student:
pass
student = Student()
newName = input('Inserire nome:')
setattr(student, 'name', newName)

Accessing a method of a parent class in the sublass

i am new to OOP.
i have a parent class with a method that i wanna access in my subclass. But i cannot figure out the right syntax for that. I cannot find a clear cut example anywhere
Members in the base class are simply available to the subclass as well (unless they are overwritten):
class Base:
def example (self):
print('This is in the base class')
class Subclass (Base):
def test (self):
self.example()
An object of type Subclass can now access example directly or indirectly:
>>> x = Subclass()
>>> x.test()
This is in the base class
>>> x.example()
This is in the base class
class Parent(object):
def __init__(self, name):
self.name = name
def output(self):
print self.name
class Child(Parent):
def __init__(self, name, age):
Parent.__init__(self, name)
self.age = age
def output(self):
super(Child, self).output()
print self.age
if __name__ == '__main__':
a = Parent("wy")
b = Child("zhang", 10)
a.output()
b.output()
You can try this code.

Categories