python assigment -5
readlines()
This method will read the entire content of the file at a time.
This method reads all the file content and stores it in the list.
This method reads up to the end of the line with readline () and returns a list.
Code Implementation with readlines()
#open the file for read operation fl = open('pythonfile.txt') # reads line by line and stores them in list for ln in fl.readlines(): print(ln) #close the file fl.close()
readline()
This method will read one line in a file.
A new line character is left at the string end and is ignored for the last line provided the file does not finish in a new line.
This method reads up to the end of the line with readline() and returns a list.
Example
Code Implementation with readline()
#open the file for read operation fl = open('pythonfile.txt') # reads line by line ln = fl.readline() while ln!= "": print(ln) ln = fl.readline() #close the file fl.close()
2)
Defining a Class in Python
Like function definitions begin with the def keyword in Python, class definitions begin with a class keyword.
The first string inside the class is called docstring and has a brief description of the class. Although not mandatory, this is highly recommended.
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# Output: 10
print(Person.age)
# Output: "This is a person class"
print(Person.__doc__)Output
10 This is a person class
Creating an Object in Python
We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class. The procedure to create an object is similar to a function call.
>>> harry = Person()This will create a new object instance named harry. We can access the attributes of objects using the object name prefix.
Attributes may be data or method. Methods of an object are corresponding functions of that class.
This means to say, since Person.greet is a function object (attribute of class), Person.greet will be a method object.
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# create a new object of Person class
harry = Person()
# Calling object's greet() method
# Output: Hello
harry.greet()Output
Hello
3)
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for better understanding about the topic.
Example 1:
Output:
Geeks True
python assignment 4 : - assignment -4
