Python Forum

Full Version: Trying to understand the python code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I am a beginner. I have written this code and it works for some part while it doesn't work the other time. Kindly help.

class Employee: def __init__(self, full_name, age ): self.full_name = full_name self.age = age def shout(self): print(f"the details of employee is , {self.full_name} and the age is {self.age}") def run(self): return self empl_1 = Employee("Suman Palisetty", 37) # empl_2 = Employee("Suman Palisetty", 38) # empl_1.shout() # empl_2.shout() print(empl_1.run()) #It gives me <__main__.Employee object at 0x000002952C978400> # print(Employee.run()) '''if we uncomment this line and run it, it gives me this error.
Error:
Traceback (most recent call last): File "C:/Users/spali/PycharmProjects/First/decorator1.py", line 18, in <module> print(Employee.run()) TypeError: run() missing 1 required positional argument: 'self' '''
What am I doing wrong, why it doesn't work for me?

</code>
Your Employee.run() method returns self - that is the instance of the class. So with print(empl_1.run()) you get <__main__.Employee object at 0x000002952C978400> what is expected.

run() is instance method, it expects to get [automatically] instance of the class as firs argument self. If you run print(Employee.run()) run it does not get such instance and you get the error.

Now it's unclear what you actually expect run() method to do. Care to elaborate, so that we can be of more help?
The way to use classes are via objects. This means that Employee is just like a name for your class, like a title. The way you use the class is by initializing an object. This is done by this code:
empl_1 = Employee("Suman Palisetty", 37)
. This makes empl_1 an object from the class Employee, meaning to say that empl_1 is able to use the methods defined in the Employee class. However, the Employee class itself is not meant to be called to use a method.

I'll give you another example:
Lets say I create a class called Money with initializer method def __init__(self, value)
And lets say I create a method called deposit() that deposits the money
I will initialize an object called Five dollar note by doing Five_Dollar_Note = Money(5) #Assigning value of 5
I will also initialize another object called Ten dollar note by doing Ten_Dollar_Note = Money(10) #Assigning value of 10
To use my deposit function, I will do Five_Dollar_Note.deposit() or Ten_Dollar_Note.deposit() instead of Money.Deposit()
because you can deposit a 5 dollar note, or a 10 dollar note, but you don't deposit "money". However, 5 dollar note and 10 dollar note are both "money"
I don't know if I did a good job explaining it but I hope you understand.