Python Forum

Full Version: extracting data
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am new bie. I have written small code here. how can I print first name from function directly from instance


class Test:
    def __init__(self,first,last):
        self.first=first
        self.last=last
    def display_first(self):
        return '{}'.format(self.first)

    def display_Last(self):
        print("Last name:",self.last)

Emp1=Test

Emp1.first="Ajit"
Emp1.last="Nayak"

print(Test.display_first(Emp1))
print(Emp1.display_first())
#Emp1.display_first()
You're not calling the constructor properly. You're setting Emp1 to the class itself, not an instance of the class.

I would prefer for something like this to not bother with a method, just print the attribute directly. But you can create a method to return or to print it. Here's a simplification of what you were doing earlier.

class Test:
    def __init__(self,first,last):
        self.first=first
        self.last=last

    def display_first(self):
        return '{}'.format(self.first)

    def display_Last(self):
        print("Last name:",self.last)

Emp1=Test("Ajit", "Nayak")

print(Emp1.first)
print(Emp1.display_first())
Output:
Ajit Ajit