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 of that class:

person1 = name("jean")
person2 = name("dean")

I know, that is not possible, but how can I pass an input-argument into an instance of a class?

This question is tagged with python oop

~ Asked on 2016-06-15 14:00:50

The Best Answer is


>>> class name(object):
...     def __init__(self, name):
... = name
>>> person1 = name("jean")
>>> person2 = name("dean")

~ Answered on 2016-06-15 14:04:43


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

class name(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.

class name(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, and use that in any other method in the class without needing to pass it to the method.

For example:

class name(object):
  def __init__(self, name): = name
  def PrintName(self):

a = name('bob')

~ Answered on 2016-06-15 14:10:41

Most Viewed Questions: