程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python interview questions_ Chapter (4)

編輯:Python

List of articles

      • 1. How to expand a two-dimensional list into a one-dimensional list through a line of code
      • 2. How to integrate python To bytes type
      • 3. To be specific Python Medium any and all Usage of
      • 4. How to convert two lists into a tuple list
      • 5. Python Introspection mechanism
      • 6. List a few Python Common magic methods and explain their uses
        • ① What is the magic method ?
        • ② The three most commonly used magic methods related to the creation and destruction of objects
        • ③ functor `__call__() Method `
        • ④ Class `__str__`,`__repr__`

1. How to expand a two-dimensional list into a one-dimensional list through a line of code

  • analysis

    1. Use double-layer loop list derivation
    2. Use sum(iterable,start=0), Be careful sum The function takes a default parameter , The default is 0
    3. Use numpy Medium flatten() function
    4. Use itertools Medium chain

2. How to integrate python To bytes type

  • analysis

    1. Use it directly b' character string ' In the form of
    2. Use character string .encode() Method
    3. bytes(str,encoding="utf-8")

3. To be specific Python Medium any and all Usage of

  • any

    1. Prototype any(iterable,/), The function of underline : The parameters before declaring this function can only be positional parameters
    2. effect return True If bool(elem) by True , For arbitrary iterable Inside elem Come on
    3. If it is iterable It's empty. , Then return to False

  • all(iterable,/)

    1. return True, If iterable Everything in it elem Of bool(elem) All back to True When , The result is True
    2. similar and The role of
    3. Be careful : If iterable It's empty , be all The return value of True

4. How to convert two lists into a tuple list

5. Python Introspection mechanism

  • What is? Python The introspection mechanism of

    1. python At run time, you can get the types and properties of objects
    2. python Is a strongly typed dynamic language , Strong type means python Implicit type conversions are rarely used , Dynamic language means python It is allowed to change the type of object at runtime
  • dir()


    Translate :

    1. dir([object]) -> String list
    2. Call... Without parameters , Returns the name in the current scope
    3. If there are parameters , This parameter must be an object . What is returned is the property of the object , In alphabetical order
    4. If the object overrides __dir__() Method , The overridden , No, call the default dir() Method
    5. For module objects , Returns the properties of the module
    6. For class objects , Returns the properties of the class , And the properties of the parent class
    7. For any other object , Return object properties , Class attributes and base class attributes

  • __dict__

    1. If it is an instance object, call , Returns the properties in the instance object ( Method does not return ), Properties in the parent class are not returned
    2. If it is a class object call , The properties and methods of the class object are returned , Similarly, inheritance is not considered

  • __name__

Not all objects have names , But those objects that have names store their names in their __name__ Properties of the . notes : The name is derived from the object, not from the variable that references it .


The module has a name ,Python The interpreter itself is considered a top-level module or a main module . When running interactively Python When , Local __name__ Variables are assigned values __main__. Same drop , When executed from the command line Python modular , Instead of importing it into another module , Its __name__ Attribute is assigned a value __main__, Instead of the actual name of the module . such , Modules can view their own __name__ Values to determine for themselves how they are being used , As support for another program , Or as the main application executed from the command line . The following idiomatic statements are used in Python Is very common in :

if __name__ == "main":
# do something test
else:
# do nothing
  • type

type() Function helps us determine what kind of object is , Its return value is the type object :

  • id( Address / identification )
    I said before , Each object has an identifier , Type and value . It is worth noting that , There may be multiple variables that reference the same object , similarly , Variables can be applied that look similar ( Have the same type and value ), Single multiple objects with distinct identities . When changing objects , For example, add an item to the list , This concept of object identification is particularly important , As in the example below ,blist and clist Variables refer to the same list object .id() Function returns a unique identifier for any given object .

attribute
Object has properties , also dir() The function returns a list of these properties . But sometimes , We just want to test 1 Whether one or more attributes exist . If the object has the properties we are considering , Then you usually want to retrieve only this attribute . This task can be performed by hasattr() and getattr() Function to complete .

Callable

You can call to represent potential behavior ( Functions and methods ) The object of . It can be used callable() Function to test the callability of an object :

example
stay type() Function provides the type of the object , You can also use isinstance() Function test object , To determine if it is an instance of a particular type or custom class :


Subclass

Questions about classes , There is a concept of inheritance , If there is inheritance, there is the problem of father and son , This is normal in real life , The same is true in becoming a language .
In an inherited relationship , A key concept is attributes , The subclass will inherit the properties of the parent class . So if you decide whether a class is a subclass of another class ?
have access to issubclass() To judge , Pay attention to the judgment here , It is also a subclass of itself .

The following is an example to illustrate the concepts and knowledge used in this article :

Sometimes we meet the need , Need to execute some method of the object , Or assign a value to a field of the object , However, the method name and field name cannot be determined when encoding , You need to pass in a string as a parameter . Take a specific example : When we need to implement a universal DBM When the framework , You may need to assign values to fields of data objects , But we can't predict what fields the data objects using this framework have , In other words , When we write a framework, we need to access unknown properties through some mechanism .

This mechanism is called reflection ( The object itself tells us what properties it has ), Or introspection ( The object itself can know which properties it has ), It is used to obtain object information at run time .

1) Properties of the access object

  • dir(obj)

Call this method to return a return containing obj List of most property names ( There will be some special properties that are not included ).obj The default value of is the current module object .

  • hasattr(obj,attr):

This method is used to check obj Is there one named attr The property of the value of , Returns a Boolean value .

  • getattr(obj,attr):

Calling this method will return obj Middle name is attr The value of the property of value , For example, if attr by bar, Then return to obj.bar.

  • setattr(obj,attr,val):

Calling this method will give obj The name is attr The value attribute of is assigned to val. For example, if attr by bar, Is equivalent to obj.bar=val.

Access the metadata module of the object (module)

  1. __doc__: docstring . If the module has no documentation , This value is None.
  2. __name__: Always the module name at the time of definition , Even if you use import as Nicknamed it , Or assign to another variable name .
  3. __dict__: Contains the attribute names available in the module - A dictionary of attributes ; That is, you can use the module name . Object accessed by property name .
  4. __file__: Contains the file path of the module . It should be noted that the built-in module does not have this attribute , Accessing it throws an exception .


example (instance)

Instance refers to the object after class instantiation .

  • __dict__: Contains the available attribute names - Attribute dictionary .
  • __class__: The class object of this instance

Built in functions and methods (built-in functions and methods)

According to the definition , The built-in (build-in) Module means to use C Write the module , Can pass sys Modular builtin_module_names Field to see which modules are built-in . The functions and methods in these modules can use fewer attributes , However, there is generally no need to view their information in the code .

  • __doc__: Documentation of functions or methods
  • __name__: The name of a function or method when it is defined
  • __self__: Only methods are available , If it is bound (bound), Then point to the class that calls the method ( If it's a class method ) Or instance ( If it's an example method ), Otherwise None
  • __module__: The module name of the function or method

function (function)

This refers specifically to non built-in functions . Be careful , Use... In classes def The definition is method , Although methods and functions have similar behavior , But they are different concepts .

  • __doc__: Documentation for functions ,
  • __name__: The name of the function when the function is defined
  • __module__: Contains the module name that defines the function , Also note that , It's the module name, not the module object .
  • __dict__: Available properties of function

6. List a few Python Common magic methods and explain their uses

① What is the magic method ?

First, remember the key memory :

  1. __somename__ Start with double underscore , Double underlined member functions .
  2. Programmers don't have to call ,Python The interpreter calls itself at the appropriate time or under specific circumstances .
  3. My understanding : The magic method is actually such a method , yes Python An embodiment of grammar , A certain fixed syntax will call certain magic methods .

② The three most commonly used magic methods related to the creation and destruction of objects

  • 1) __init__():

When creating objects __init__() Will be called automatically , It is used to initialize the instance property according to the passed parameters .
It is itself an initialized function , It's not a constructor .

  • 2) __new__():
  1. When an object is created, it first calls __new__() Method to create a class and return an instance of this class .
  2. __new__ At least one parameter cls, Represents the current class , This parameter is instantiated by Python The interpreter automatically recognizes
  3. __new__ There must be a return value , Return the instantiated instance , This is achieved by myself __new__ We should pay special attention to it , Sure return Parent class ( adopt super( The name of the class ,cls))__new__ Come up with examples , Or directly object Of __new__ The examples come out .
  4. If __new__ Create an instance of the current class , Automatically called __init__ function , adopt return Statement __new__ The first argument to the function is cls To ensure that it is an instance of the current class , If it's the class name of another class , Then the actual creation returns instances of other classes , In fact, the current class will not be called __init__ function , Also won't whine with other kind of _init__ function


You can see that second one does not call __init__ Method , because __new__ Method does not create an object and returns , therefore __init__() Method objects can be instantiated .


3) __del__ function

Destroy the instantiated object , This is the destructor .
When to call : Automatically triggered when memory is reclaimed , There are two situations in which memory is reclaimed :

  1. Reclaim all variables after page execution
  2. All objects are del When
class Bird(object):
def __init__(self, name):
self.name = name
def fly(self):
print("{} Birds are flying !".format(self.name))
def __del__(self):
print("{} The bird is dead , Is deconstructed !".format(self.name))
dark = Bird(" The duck ")
dark.fly()

result :

All objects are del When :

③ functor __call__() Method

Timing of invocation :

  1. Automatically triggered when an object is called as a function
  2. You can simulate functional operations
  3. It is similar to overloading in a class () Operator , The instance object can be called like a normal function , With Object name () In the form of .

for instance :


If you want a class object , If it can be called as a function, it must be defined __call__ Method , such as :

You can see , By means of Student Class __call__ Method , bring Student The instance object of becomes a callable object .
Python in , Anyone who can () Apply directly to itself and execute , Are called callable objects . Callable objects include custom functions ,Python Built in functions and class instance objects mentioned in this section .

For callable objects , actually name (), It can be understood as name .__call__() Abbreviation . Still take the above example , The last line of code is actually equivalent to :


Then an example of a custom function :

④ Class __str__,__repr__

  • __str__
  1. effect : Returns a string object , A string that is primarily user-friendly
  2. Timing of invocation : 1> str(obj) 2> format() 3> print()
  • __repr__:
  1. effect : The official string form used to output an object . The return value must be a string object , It is usually used to show the interpreter .
  2. Timing of transfer : 1> repr() Built in function call

Be careful :

If __repr__ Already defined , and __str__ Undefined , Then the object calls __str__ = __repr__.


Next, if __str__ When it's undefined , be __repr__ Will be called


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved