There are more than 8 million Python developers worldwide. Thousands of new learners join the Python community every day. The harsh truth is that only 10-20% of people will ever be a good developer and get a good job. The reason is that they can’t solve some advanced interview problems. Next, I’m going to share with you 10 important Python questions that are frequently asked.
1. .py
和 .pyc
What’s the difference?
The.py file is the source code of the program. Pyc files are compiled bytes of the program.
Python compiles the.py file and saves it as a.pyc file. It is then executed by the Python virtual machine.
Before executing the main source code, Python looks for its compiled version (the.pyc file), and if Python finds it, it executes it with the help of the virtual machine. If not, it will look for a.py file and compile it and then execute the.py file. Basically,.pyc files save compilation time by executing the compiled code again.
2. What is abstraction? How do you implement abstraction in Python?
Abstraction is used to hide the internal functionality of a function from the user. They can interact with functions and generate results, but have no idea how the results are generated.
In simple terms, abstraction is used to hide irrelevant data from the user to reduce the complexity of the program. With the ABC module in Python, we can achieve abstraction.
Abstract classes can also serve as building blocks for other classes, because you can’t create objects for abstract classes, so the only way to access elements is to use inheritance.
from abc import ABC, abstractmethod
class Parent(ABC) :
@abstractmethod
def show(self) :
pass
class child(Parent) :
def show(self) :
print("Child Class")
obj = child() Abstract classes cannot be instantiated
obj.show() # Child Class
Copy the code
3. What is FrozenSet? Give an example of its importance.
FrozenSets are similar to sets, except that they are immutable.
You can modify the elements of a set at any time, but frozenSet cannot be modified once created.
This means that no element can be added, deleted, or updated after creation. Frozenset takes iterable objects as input and makes them immutable. Since frozen sets are immutable, they can be used as keys in a dictionary.
data = {"Name": "Roger"."Pin": 3056."ActNo":9892345112234565}
fSet = frozenset(data)
print(fSet) # frozenset({'Name', 'Pin', 'ActNo'})
Copy the code
4. What are the differences between shallow copy and deep copy?
Shallow copy stores a reference to an object in a new memory location. Changes made to the new location are also reflected in the previous location. It’s faster than deep copy.
Deep copy stores the value of an object in a new location. Any changes made to the new location will not be reflected in the previous location.
Id Is used to view the memory address of an object. Of course, the address of the following example will be different on your computer.
# # shallow copy
data = [1.2.3.4.5]
updated_data = data
updated_data.append(6)
print(updated_data) # [1, 2, 3, 4, 5, 6]
print(data) # [1, 2, 3, 4, 5, 6]
print(id(data)) # 16777216
print(id(updated_data)) # 16777216
# # deep copy
import copy
data = [1.2.3.4.5]
updated_data = copy.deepcopy(data)
updated_data.append(6)
print(updated_data) # [1, 2, 3, 4, 5, 6]
print(data) # [1, 2, 3, 4, 5]
print(id(updated_data)) # 16777216
print(id(data)) # 14020317
Copy the code
5. How is pickle used?
Pickling is the process of converting a Python object into a byte stream, often called serialization.
Unpickling is the inverse operation that converts the byte stream into a Python object, often called deserialization.
In Python we use pickle.dump and pickle.load for serialization and deserialization.
## Pickling
import pickle
data = {
'Names': ["Karl"."Robin"."Lary"].'Id': ('G770531'.'G770532'.'G770533'),
'Salary': [55600.88900.76000]
}
output = open('./data.pkl'.'wb')
pickle.dump(data, output)
output.close()
## Unpickling
import pickle
stream = open('./data.pkl'.'rb')
data = pickle.load(stream)
print(data) # {'Names': ['Karl', 'Robin', 'Lary'], 'Id': ('G770531', 'G770532', 'G770533'), 'Salary': [55600, 88900, 76000]}
stream.close()
Copy the code
Parameters of 6.*args
and**kwargs
What is?
*args and **kwargs both allow a variable number of arguments to be passed to a function. They are used when there is uncertainty about the number of arguments to pass in a function.
* ARgs allows you to pass a variable number of arguments to a function.
def addNumbers(*numbers) :
sum = 0
for number in numbers:
sum = sum + number
print("Sum: ".sum)
addNumbers(3.5) # Sum: 8
addNumbers(5.6.7) # Sum: 18
Copy the code
** Kwargs allows you to pass a variable number of keyword arguments to functions.
def addNumbers(**data) :
sum = 0
for key,value in data.items():
sum = sum+value
print("Sum: ".sum)
addNumbers(a=5, b=6) # Sum: 11
addNumbers(a=5, b=8, c=10) # Sum: 23
Copy the code
7. How to understand resource managers in Python?
Context managers are used for resource management. They allow you to allocate and release resources as needed. The most commonly used and recognized example of a context manager is the with statement. It is mainly used to open and close files. With allows you to open and close files when a single line has problems. Its main advantage is that it ensures that files are closed correctly.
with open ('./data.txt'.'w') as f:
f.write("Hello")
Copy the code
8. How to understand instance methods, class methods, and static methods in Python?
In Python, you can define three methods — instance methods, class methods, and static methods.
-
Instance methods: are normal methods that we create when we create a class. These methods are object specific. The syntax for these methods is def do_something(self), where self refers to the instance object.
-
Class methods: Slightly different from instance objects. They bind to the class, not the object of the class. These are used to perform class tasks and can change the state of the class. We create a classmethod with the @classmethod decorator.
-
Static methods: Methods defined in a class, primarily for program logic clarity, are class-independent and do not require an instance of a class. We create a staticmethod with the @staticmethod decorator.
9. What isnolocal
andglobal
Variable?
They are used to define the scope of a variable. Global is a variable defined outside the scope of a function. The value of this variable is the same for the entire code. It can be used anywhere in the program.
pi = 3.14 ## Global variables
def circle(radius) :
area_of_circle = pi * (radius) ** 2
print("The area of the circle is: ", area_of_circle)
circle(7) # The area of The circle is: 153.85
Copy the code
NonLocal is a variable used in nested functions that have no local scope defined. If you change the value of a non-local variable, the value of a local variable also changes.
def outer_function() :
x = "local_variable"
def inner_function() :
nonlocal x
x = "nonlocal_variable"
print("inner function:", x)
inner_function()
print("outer function:", x)
outer_function()
# inner function: nonlocal_variable
# outer function: nonlocal_variable
Copy the code
10. Give examples of Generator?
Generators are functions that return an iterable. Generator functions must contain at least one yield statement. Yield is a keyword in Python used to return a value from a function without breaking its current state or a reference to a local variable. Functions with the yield keyword are called generators.
A generator generates an item only once when it is asked to execute. They are memory efficient and take up less memory space.
For starters, yield can be interpreted as another form of return, but it does not stop the execution of a function; instead, it returns a value.
def fibon(limit) :
a,b = 0.1
while a < limit:
yield a
a, b = b, a + b
for x in fibon(10) :print(x) # 1 2 3 5 8 13 21 34 55 89
Copy the code
section
I’ve shared 10 frequently asked Python interview questions in the hope that you’ll find them helpful if you’re looking for a new job or looking for one someday!
Welcome everyone to like, favorites, support!
Pythontip, Happy Coding!
Public number: quark programming
Click here to run the code