Created
October 17, 2017 17:40
-
-
Save venkatsgithub1/b27912df1ab7b43d3d7cacb414f4a182 to your computer and use it in GitHub Desktop.
Creating a simple class in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person: | |
"""A simple class in Python""" | |
def __init__(self, name, age): | |
""" | |
The function __init__ is like a | |
constructor for the class. | |
""" | |
self.name = name | |
self.age = age | |
def __str__(self): | |
""" | |
Compare this function to | |
toString method in java. | |
If a python instance variable is directly | |
printed, one can see approparite formatted | |
information returned by this method. | |
""" | |
return "Person Object(Name:{}, Age:{})".format(self.name, self.age) | |
def __repr__(self): | |
""" | |
The method is mostly used by developers. | |
When __str__ is not used in class, string | |
returned by __repr__ is printed. | |
""" | |
return "Person (Name:{}, Age:{})".format(self.name, self.age) | |
person1 = Person("John Doe", 25) | |
print(person1) | |
print(person1.age) | |
print(person1.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment