Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python class input argument

Tags:

python

oop

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?

like image 476
lars111 Avatar asked Jun 15 '16 14:06

lars111


People also ask

Can Python classes take arguments?

By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.

How do you pass an argument to a class in Python?

Methods are passed as arguments just like a variable. In this example, we define a class and its objects. We create an object to call the class methods. Now, to call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name.

How do you input a class in Python?

It is to be noted that while using class in Python, the __init__() method is mandatory to be called for declaring the class data members, without which we cannot declare the instance variable (data members) for the object of the class.

Can classes take parameters?

A class parameter defines a special constant value available to all objects of a given class. When you create a class definition (or at any point before compilation), you can set the values for its class parameters.


1 Answers

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 self.name, 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):     self.name = name   def PrintName(self):     print self.name  a = name('bob') a.PrintName() bob 
like image 168
AbrahamB Avatar answered Sep 23 '22 08:09

AbrahamB