Python Class - Create Class Object - Access Properties & Functions
Python - Create class object
Consider the following class Laptop
. We shall create an object of type Laptop
in the example program.
In the following code snippet, we have defined the class Laptop
with properties and methods.
class Laptop:
name = 'My Laptop'
processor = 'Intel Core'
@staticmethod
def start():
print('Laptop is starting..')
@staticmethod
def restart(self):
print('Laptop is restarting')
def details(self):
print('My laptop name is:', self.name)
print('It has',self.processor,'processor.')
where
- name and processor are properties.
- start(), restart() and details() are methods. Of these start() and restart() are static methods.
Now, we shall create an object of user defined class type Laptop
.
Python Program
class Laptop:
name = 'My Laptop'
processor = 'Intel Core'
@staticmethod
def start():
print('Laptop is starting..')
@staticmethod
def restart(self):
print('Laptop is restarting')
def details(self):
print('My laptop name is:', self.name)
print('It has',self.processor,'processor.')
#create object
laptop1 = Laptop()
laptop1.name = 'Dell Alienware'
laptop1.processor = 'Intel Core i7'
laptop1.details()
The line laptop1 = Laptop()
creates an instance of the class Laptop
and is stored in laptop1
.
Laptop()
is the constructor used to initialized the object.
Output
My laptop name is: Dell Alienware
It has Intel Core i7 processor.
Summary
In this tutorial of Python Examples, we learned how to create an object of user defined class type, with examples.