Seventh day of Python cultivation

Source: Internet
Author: User
Tags sha1 string back string to file

Tagged with: deb MD5 return IGP dump named delattr cultivation SetAttr

The seventh day object-oriented advanced, object-oriented programming understanding is still somewhat difficult, but I think if you figure out, it is much easier to program programming than functional programming. Keep trying! 1. Object-oriented supplement: encapsulation
Encapsulation in the broadest sense: putting variables and functions in classes
The narrow sense of encapsulation: to hide some variables or methods, not public.

Static properties are divided into two types:
of the public:
Private: __ Name is preceded by a name with two underscores. This is public.
Like what:
Class Person:
Name = "Jack" #这个就是公有静态属性
__country = "China" #这个是私有静态属性
If it is a private property, it can only be used inside the class. Can no longer be used outside the class
If you do not want to call a private property outside of the class, then name must be preceded by a private name __ The name of the _ Class name
However, you cannot use this method to invoke a private variable.

Private variables:
Inside the class, if you use the __ variable to deform, Python automatically adds the _ Class name to you
Outside of the class, you cannot define a private variable.
Class Person:
__country = "China"
def __init__ (SELF,NAME,PWD):
Self.name = Name
SELF.__PASSWD = pwd
def login (self):
if self.name = = "Alex" and self.__pwd = "alex3714":
Print ("Login successful! ")
Private methods:
Class Person:
def __init__ (SELF,NAME.PWD):
Self.name = Name
Self.__pwd = pwd
def __eat (self):
Print ("eating")
Alex = person ()
Alex.__eat # This situation will be an error. Cannot call private method.
Application scenarios, such as cryptographic authentication.
For example, to do a cryptographic encryption algorithm
def.__ Password Converter (SELF,INP):
Print ("eating")
def.__ password (self):
INP = input ("pwd")
self.__ Password Converter (INP)
Interview questions:
Class Foo:
def __into__ (self):
Self.func ()
SEF __func (self):
Print ("in Foo")
Class Son (Foo):
def __func (self):
Print ("in Son")

s = Son ()
This will output in Foo
2. Adorner methods in a class
Three adorner functions:
Classmethod
Staticmethod
Property

1 property


2 Classmethod
If a method in a class does not use a specific property in an instance of this class
A static variable in a class is used only by a class method


3 Staticmethod
If a method does not use the properties in the object, it does not use the properties in the class
should be defined as a static method
Like what
Class Student:
@staticmethod
def login ():
Name = input ("Name:")
PWD = input ("pwd:")
If name = = "and pwd = =" "
Print ("instanced")
Student.login ()
3. Object-oriented Advanced
Reflective Focus! ******
What is reflection.
To access the value of a variable by the variable name of the string data type

1. Class name Reflection static property
2. Object name reflection object properties and methods
3. The name in the module reflection module
4. Reflect the name of the file in which you are located

X.y such a form can be reflected
Class Person:
Def eat (self):p rint ("EATUBG")
def play (self):p rint ("Play")
Alex = person ()
While True:
INP = input ("Insert")
If Hasattr (ALEX,INP):
GetAttr (ALEX,INP) ()
Use GetAttr to get a name, if the name is not in the namespace of this object, it will be an error
GetAttr's Reflection Good companion hasattr
If you use GetAttr to get a method, you can only get the memory address of this method, plus parentheses to execute
If you use GetAttr to get a property. Then you can get the value directly using reflection

reflect the name in your module:
GetAttr (sys.modules["__main__"], "value")
SetAttr is to assign a value to an object, and if so, overwrite it.
SetAttr (obj, "name", "Jack")
Delattr Deleting properties

__NEW__ create an object. This is the construction method. OBJECT.__NEW__ (CLS) first creates an Object!
__init__ Initialization method
Execute the new method first, Object.new ()
Execute the Init method again


Design Patterns-the Java design language.
Singleton mode: Only one instance of a class
__new__ is equivalent to having a child, and __init__ is the equivalent of dressing a child.
Single-row mode is only one child, but clothes can be all. Anyone can change all kinds of clothes for the child. The last dress is his clothes.
Class Person:
__insta = None
def __new__ (Cls,*args,**kwargs)
If not __insta:
Obj = Object (CLS)
__insta = obj
return obj
def __init__ (self):
Print (obj)

__STR__ can print an object without returning a memory address and returning a string. Note Only strings can be returned.


Module:
Module import, which is the execution of this file.
mymodule.py file
Money = 100
Def func1 ():
Print ("Func1")
Class Manger:
Def eat (self):
Print ("eating")
In other files, you can introduce
Import MyModule
GetAttr (MyModule, "Moeny")
GetAttr (MyModule, "func1") ()
Manger = GetAttr (MyModule, "Manger")
A = Manger ()
A.eat ()
4 Common modules:
1 Serialization Module
What does serialization mean?
{"1101": {"name": "Jack", "Age": $, "class": "1101"}}
Procedure for data type--------strings
Why use serialization?
Easy data from memory to file
Data transfers bytes on the network--string--Dictionary
What are the serialization modules in Python?
JSON general support has fewer data types. List Tuple dict container types
Pickle is common in python. Almost all data types in Python are supported
Shelve Python uses the boundary of the serialization tool Py2 and PY3 conversion may be problematic. So use less.

There are four ways to serialize:
Memory-based:
Dumps process---Serialization of data type to string
Loads string transfer other data types---deserialization
File-based:
Dump converts data type to string to file---serialization
Load reverses the string back to the data type from the file---deserialization
If you want to dump more than one piece of data:
With open ("A.txt", "W") as F:
Str_dic = Json.dumps (DIC)
F.write (str_dic+ "\ n")
F.write (str_dic+ "\ n")
Read more than one piece of data:
With open ("A.txt") as F:
For line in F
Print (Json.loads (Line.strip ()))

When storing objects, reads can be used:
With open ("A.txt", "RB") as F:
While True:
Try
obj = Pickle.load (f)
Print (obj)
Except Runerror
Break

2 hashlib have to be
such as storing user passwords
When storing passwords, do not use clear text, you need to do a calculation of the user input password, the calculation will get a new fixed string
Gets a string of 16 binary strings.
This requires the use of the Hashlib module
Hashlib Features:
A string is summarized and a fixed value is obtained.
Multiple algorithms with a sum
The ability to have a string that uniquely corresponds to a fixed value
Hashlib How to use:
Use scenario 1: Password encryption verification, verification.
HASHLIB.MD5 () #md5算法.
Md5obj = HASHLIB.MD5 ("Tesla". Encode ("Utf-8")) #实例化一个md5摘要. This can add some salt.
# There's also dynamic add salt. Use the account name as Salt Plus. But there's no way to change the account.
Md5obj.update ("alex3714". Encode ("Utf-8")) # Manipulating strings using MD5 algorithm objects
ret = Md5obj.hexdigest () # Gets the result of the algorithm is Hex + Digest digest +16 Binary
HASHLIB.SHA1 () #sha算法
Sha1obj = HASHLIB.SHA1 ()
Sha1obj.update ("ABCDEFG". Encode ("Utf-8"))
ret = Sha1obj.hexdigest ()
Use Scenario 2: Verify the consistency of the file.




3 Configparse
Config.options ("bitbucket.org") with the For Loop finds all keys under Bitbucket,ort
Config.items ()
Config.get ()
Config.remove_setion
Config.remove_option
Config.set ("topsecret.server.com", "K1", "111111")
Config.set ("Yuan", "K2", "222222")

4 logging have to be
Log module: Program error---Log to see internally.
External view of user behavior, and so on.
Import logging
#简单配置, but not friendly to Chinese.
Logging.debug ("debug Message") #非常细节的日志 use when troubleshooting errors----
Logging.info ("info message") # Normal log information, operation record, etc.
Logging.warning ("warning message") # Small system problem, but can function properly
Logging.error ("error message") # has not been processed properly. However, you can pass some try processing to get past the error.
Logging.critical ("critical Message") # Fatal error. L cannot be used normally.
Use:
Logging.bashconfig (level=logging. DEBUG
format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ')


#logger对象的方式配置----General use of this configuration is better for Chinese support.
#有点类似吸星大法
Loggers = Logging.getlogger ()
# Enter in file
FH = logging. Filehandler ("Log.log", encoding= "Utf-8") #创建了一个能操作文件的对象fh, pay attention to specifying the Chinese encoding.
Loggers.addhandler (FH)
Loggers.debug ("warning message")
# Enter on the screen
SH = logging. Streamhandler ()
Loggers.addhandler (SH)
Loggers.warning ("warning message")
# format is not good to see can also customize the format:
FH = logging. Filehandler ("Log.log")
Formatter = loggers. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ')
Fh.setformatter (Formatter)
Loggers.addhandler (FH)
#

# If you want to output that level you can adjust:
Fh.setlevel (loggers. DEBUG)
Also note that you need to modify the level of loggers if you want to output levels down
Loggers.setlevel (logging. DEBUG)


Seventh day of Python cultivation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.