Python classes and objects

python classes and objects
Photo by Shahadat Rahman on Unsplash

Create a class:

## Syntax
class className:
'''
Body of class
'''
pass
# Define a class
class Tourist:
'''
Defining a new Tourist class
'''
def __init__(self, name, age):
self.name = name
self.age = age

## Instance method
def sayHello(self):
print("Hello, my name is " + self.name)
print("Hello, my ageis " + str(self.age))
# Object instantiation
t1 = Tourist("John", 36)
t1.sayHello()
print(t1)
Hello, my name is John
Hello, my age is 36
<__main__.Tourist object at 0x000001360A791730>
t2 = Tourist(“Smith”, 27)
t2.sayHello()
print(t2)
Hello, my name is Smith
Hello, my name is 27
<__main__.Tourist object at 0x000001360A7A5460>
t1 == t2
False
t3 = Tourist()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-c4ac6fc04fcc> in <module>
----> 1 t3 = Tourist()

TypeError: __init__() missing 2 required positional arguments: 'name' and 'age'

--

--

Software Developer | Machine Learning Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store