[Tutor] Help on class
Dave Angel
davea at davea.name
Sat Sep 28 01:39:33 CEST 2013
On 27/9/2013 10:07, bharath ks wrote:
> Hello,
>
> May i know why object 'c' does not prompt for employee name and employee id in the following code
> i get out put as
>
> Enter employee name:john
> Enter employee id:56
> Employee name is: john
> Employee id is: 56
> ----------------------------------------------------
> Employee name is: test
> Employee id is: 1003
> ----------------------------------------------------
> Employee name is: john
> Employee id is: 56
>
> class employee:
>
> emp_name=""
> emp_id=0
Those 2 class attributes are never used. Good thing, since you really
want each employee to have his own name.
> def collect_name():
> return(input("Enter employee name:"))
>
>
> def collect_id():
> return(input("Enter employee id:"))
>
> def show(self):
> print("Employee name is:",self.emp_name)
> print("Employee id is:",self.emp_id)
>
> def __init__(self,name=collect_name(),id=collect_id()):
Those 2 function calls will happen only once, long before you
instantiate any instance of employee. Put those inside the method, not
as default values.
> self.emp_name=name
> self.emp_id=id
>
>
>
> a=employee()
> a.show()
> print("----------------------------------------------------")
> b=employee("test",1003)
> b.show()
> print("----------------------------------------------------")
> c=employee()
> c.show()
>
The __init__() method should look something like this. That way,
collect_name() and/or collect_id() will be called if the corresponding
argument is not given.
def __init__(self,name = None, id=None):
if name:
self.emp_name=name
else:
name=collect_name()
if id:
self.emp_id=id
else:
self.id=collect_id()
>
> <html><body><div style="color:#000; background-color:#fff; font-family:times new roman, new york, times, serif;font-size:10pt"><div><font size="2">Hello,</font></div><div><font size="2"><br></font></div><div><font size="2">May i know why object 'c' does not prompt for employee name and employee id in the following code</font></div><div><font size="2">i get out put as </font></div><div><font size="2"><br></font></div><div><font size="2">Enter employee name:john</font></div><div><font size="2">Enter employee id:56</font></div><div><font size="2">Employee name is: john</font></div><div><font size="2">Employee id is: 56</font></div><div><font size="2">----------------------------------------------------</font></div><div><font size="2">Employee name is: test</font></div><div><font size="2">Employee id is: 1003</font></div><div><font size="2">----------------------------------------------------</font></div><div><font size="2">Employee name is:
Please switch to text mail, as the html will mess things up, sooner or
later.
--
DaveA
More information about the Tutor
mailing list