Skip to content Skip to sidebar Skip to footer

Python Getting A Variable In A Class

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 the

Solution 1:

I would separate the concern of storing your number from reading it in from command line. I assume you have something else to achieve with your example class.

defread():
    a = float(input('Give me a number: '))
    return a

classExample:
    def__init__(self,number):
        self.number = number

exampleNumber = Example(read())

print'The number is %i' % exampleNumber.number

Solution 2:

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:

classExample:
    def__init__(self, number):
        self.number = number

    @classmethoddeffrom_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.

Solution 3:

First you initialize the instance ("make me a new example!")

ex = example()

Then you can use its methods:

exampleNumber = ex.read()

You don't need to pass a as an argument, since it will be stored in the instance. Just do something like this:

defread(self):
   self.a = float(input('Give me a number) '))
   return self.a

Solution 4:

There are many ways , here. But, primitively, read the no. outside the class as`

classExample:
    def__init__(self, number):
        self.number = number

num = float(input())
exam = Example(num)

and you'd like to define get, edit,etc methods within the class

or perhaps instead of passing the number in the constructor, you can call input() immediately within constructor as:

def__init__(self):
    self.number = float(input())

Solution 5:

Gee, boy ... i do not even know where to start.

First DO NOT start with OOP! OOP is in more cases then not understood completely false. It almost always evolves around "abstractions" and "class hierarchies". It does not help that even the "ISO" got it wrong (ISO/IEC 2382-15). (See Alan Kays remarks on this issue, who coined the term object oriented.)

Jack Diederich gave a fantastic talk about OOP and class hysteria at PyCon US 2012.

But for the sake of your question let us dissect what you got:

classexample:

introduces an object of the type classobj, or type (depending on the Python version) in the current namespace. And example is already an object of it's own and not a 'pure' class in the classic "blueprint" sense, but more like a prototype. You could operate on and with the class, without to instantiate an object from it.

Next:

def__init__(self, number):
    self.number = number

__init__ is often called a constructor, because it is (almost) the closest thing to it, but still it is not a constructor in a "classical" sense. It does not "create" the object/instance, but merely initializes it. To do it, the method needs to know which instance of the many example instances it should work with. Therefore every method, which works on instances gets an implicit first argument, called self by convention, which holds a reference to the instance, which is you want to work with. If you call someobj.some_method("some argument") it gets implicitly translated to something like:

class.some_method(someobj, "some argument")  # someobj -> self

That is a somewhat crude oversimplification, but it explains the method-signature as defined in the class-declaration.

So if you refer to an attribute of an instance you do it by putting a self. as in self.number before the specific instance attribute (number). You could name it like you want, but you should keep to convention and name it self. self is like this in other languages.

Let us jump ahead to:

exampleNumber = example (read())

You create an identifier (not a variable, python has no classical variables!) named exampleNumber and assign a new object of the type example to it and ... huuh? Where does read come from? It's not a python built-in nor is it a keyword. Do you mean the method read from the class example?? Do you really try to drive in a car, which is not yet build? And on top of that you would need to call it example.read("some argument here") or exampleNumber.read("some bogus Argument here").

First things first:

  1. instantiate and initialize your object:

    exampleNumber = example(1)

  2. then you can operate on it:

    whatever = example.Number.read("curius argument")

And finally lets go over the read method:

defread(self, a):
       self.a = float(input('Give me a number) '))
       return a

You probably want to use raw_input instead of input. And you probably also want to return the object attribute a: self.a, and not the parameter-value a.

I hope i could help you somewhat, but i would strongly suggest to drop the whole OOP notion and start with structured programming. You still will use objects, because in python everything is an object, even classes and types. And later on you might start using objects as "little machines" as Alan Kay called them once and then you got the OOP paradigm right.

I did some crude oversimplifications to keep it as brief as possible, so please do not grill me over it.

Post a Comment for "Python Getting A Variable In A Class"