Skip to content Skip to sidebar Skip to footer

Python Class Input Argument

I am new to OOP. My idea was to implement the following class: class name(object, name): def __init__(self, name): print name Then the idea was to create two instances

Solution 1:

The problem in your initial definition of the class is that you've written:

classname(object, name):

This means that the class inherits the base class called "object", and the base class called "name". However, there is no base class called "name", so it fails. Instead, all you need to do is have the variable in the special init method, which will mean that the class takes it as a variable.

classname(object):
  def__init__(self, name):
    print name

If you wanted to use the variable in other methods that you define within the class, you can assign name to self.name, and use that in any other method in the class without needing to pass it to the method.

For example:

classname(object):def__init__(self, name):
    self.name = name
  defPrintName(self):
    print self.name

a = name('bob')
a.PrintName()
bob

Solution 2:

>>>classname(object):...def__init__(self, name):...        self.name = name...>>>person1 = name("jean")>>>person2 = name("dean")>>>person1.name
'jean'
>>>person2.name
'dean'
>>>

Solution 3:

You just need to do it in correct syntax. Let me give you a minimal example I just did with Python interactive shell:

>>>classMyNameClass():...def__init__(self, myname):...print myname...>>>p1 = MyNameClass('John')
John

Solution 4:

Remove the name param from the class declaration. The init method is used to pass arguments to a class at creation.

classPerson(object):
  def__init__(self, name):
    self.name = name

me = Person("TheLazyScripter")
print me.name

Solution 5:

Python Classes

classname:
    def__init__(self, name):
        self.name = name
        print("name: "+name)

Somewhere else:

john = name("john")

Output: name: john

Post a Comment for "Python Class Input Argument"