I'm learning right now a python language but I would like to programm in OOP style. Sorry for my questions but in my book and a video tutorial I couldn't find an answer. I know there is easer way to get a number without a method... but I would like to do it in a class ;)
I would like to read a number from a user.
How to write a method that take a number from a user and put it back to a constructor?
I tried this one but it isn't good :(
class example:
def __init__(self, number):
self.number = number
def read(self, a):
self.a = float(input('Give me a number) '))
return a
exampleNumber = example (read())
解决方案
As others have suggested separating the input to a standalone function would be a good way to go, but if you really want to keep the input in the class you can use a classmethod to provide an alternate constructor:
class Example:
def __init__(self, number):
self.number = number
@classmethod
def from_input(cls):
a = float(input('Give me a number: '))
return cls(a)
exampleNumber = Example.from_input()
print("The number is %i" % exampleNumber.number)
This is often considered the most Pythonic way to provide multiple constructors for a class with different incompatible parameters. Compare for example dict.fromkeys(...)
BTW, the print in your code implies you are using Python 2.x. If so you should use raw_input() to read values, or better upgrade to Python 3.x.