Python: Object Oriented advanced, python Object Oriented advanced

Source: Internet
Author: User

Python: Object Oriented advanced, python Object Oriented advanced
1. Reflection reflection: there is no security problem when using string-type names to operate on variable reflection. to operate on existing variables in the memory # attributes and methods in the reflection object

class A:    price=20print(getattr(A,'price'))

# Reflection Object Attributes

Class A: def func (self): print ('in func') a = A (). name = 'Alex 'ret = getattr (a, 'name') # print (ret) value obtained in the string form of the variable name)
# Reflection object Method
ret =getattr(a,'func')ret()

# Reflection methods:

if hasattr(A,'func')):    getattr(A,'func')()

 

# Attributes of the reflection class

class A:    price=20print(getattr(A,'price'))

# Attributes of the reflection Module

import myprint(getattr(my,'day'))
# Reflecting variables in your module
import sysprint(getattr(sys.modules['__main__'],'year'))getattr(sys.modules['__main__'],'qqxing')()

Setattr setting/modifying Variables

class A:  passsetattr(A,'name','alex')print(A,name)

Delattr

delattr(a,'name')
2 ,__ str _ and _ repr __

Change the string display of the object _ str __,__ repr __

Custom formatted string _ format __

# Double-bottom method # obj. _ str (obj) # obj. _ repr (obj)
class Teacher:    def __init__(self,name,salary):        self.name =name        self.salary =salary    def __str__(self):        return "Teacher's object :%s"%self.name    def __repr__(self):        return str(self.__dict__)    def func(self):        return 'wahaha'nezha =Teacher('nazha',250)print(nazha)print(repr(nezha))print('>>> %r'%nezha)
# The object contains a _ str __. once called, the system returns the # object memory address l = [1, 2, 3, 4, 5] # instantiate the object print (l) of a list class # % s str () directly print all actually follows _ str __# % r repr () in fact, they all follow the _ repr __# repr is the backup of str, but str cannot be used as the backup of repr # print (obj)/'% s' % obj/str (obj) in fact, obj is called internally. _ str _ method. If the str method exists, it must return a string # if there is no _ str _ method, first, the _ repr _ method in the class is found, and NO _ str _ method in the parent class is found __. # Repr (), only _ repr __will be found. If no parent class is found
Class Classes: def _ init _ (self, name): self. name = name self. student = [] def _ len _ (self): return len (self. student) def _ str _ (self): return 'classes 'py _ s9 = classes ('python full stack 9st') py_s9.student.append (' ') py_s9.student.append ('taigo') print (len (py_s9) print (py_s9)
#__ Del _ class A: def _ del _ (self): # destructor: perform some final work before deleting an object. self. f. close () a = A (). f = open () # open the file. First, open a file in the operating system and get the file operator. del a #. f The file operator is lost in the memory. del a # del executes this method and deletes the variable.
# __call__

# The object is enclosed in parentheses to trigger execution.

# Note: the execution of the constructor is triggered by the creation object, that is, the object = Class Name (); the execution of the _ call _ method is triggered by brackets after the object, that is, the object () or class ()()

Class A: def _ init _ (self, name): self. name = name def _ call _ (self): ''' print all attributes of this object: return: ''' for k in self. _ dict __: print (k, self. _ dict _ [k]) a = A ('Alex ')()
3. item Series

_ Getitem __\__ setitem __\__ delitem __

Class Foo: def _ init _ (self, name, age, sex): self. name = name self. age = age self. sex = sex def _ getitem _ (self, item): if hasattr (self, item): return self. _ dict _ [item] def _ setitem _ (self, key, value): self. _ dict _ [key] = value def _ delitem _ (self, key): del self. _ dict _ [key] f = Foo ('egon', 38, 'male') print (f ['name']) f ['hobby'] = 'male' print (f. holobby, f ['hobby']) del f. holobby # native support for object _ delattr _ del f ['hobby'] # print (f. _ dict __)
View Code4 ,__ new __
_ Init _ Initialization Method
_ New _ constructor: creates an object.
class A:    def __init__(self):        self.x = 1        print('in init function')    def __new__(cls, *args, **kwargs):        print('in new function')        return object.__new__(A, *args, **kwargs)a1 = A()a2 = A()a3 = A()print(a1)print(a2)print(a3)
Singleton Mode

# A class always has only one instance
# Create an instantiated object when you instantiate this class for the first time
# Use the previously created object when you instantiate it later
Class A: _ instance = False def _ init _ (self, name, age): self. name = name self. age = age def _ new _ (cls, * args, ** kwargs): if cls. _ instance: return cls. _ instance cls. _ instance = object. _ new _ (cls) return cls. _ instanceegon = A ('egg', 38) egon. cloth = 'huaweiao' nezha = A ('nazha', 25) print (nezha) print (egon) print (nezha. name) print (egon. name) print (nezha. cloth)

 

5 ,__ eq __
class A:    def __init__(self,name):        self.name = name    def __eq__(self, other):        if self.__dict__ == other.__dict__:            return True        else:            return Falseob1 = A('egon')ob2 = A('egg')print(ob1 == ob2)

# '=' Default memory address comparison

6 ,__ hash _ class:

Def _ init _ (self, name, sex ):
Self. name = name
Self. sex = sex
Def _ hash _ (self ):
Return hash (self. name + self. sex)

A = A ('egon', 'male ')
B = A ('egon', 'nv ')
Print (hash ())
Print (hash (B ))


7. hashlib # provides digest algorithms
Import hashlib # module that provides digest algorithms md5 = hashlib. md5 () md5.update (B 'alex3714') print (md5.hexdigest ())

1. The Digest function remains unchanged no matter how different algorithms are.

2. Use the same algorithm for digest of the same string, and the obtained value is always unchanged.

3. digest the same string using different algorithms. The obtained values should be different.

4. No matter what algorithm is used, the hashlib method will never change.

# Digest algorithm
# Password ciphertext Storage
# File Consistency Verification
# Check whether the files we downloaded are consistent with those on the remote server during the download process.
# Check whether the two files on the two machines are equal
# User Login import hashlibusr = input ('username: ') pwd = input ('password:') with open ('userinfo') as f: for line in f: user, passwd, role = line. split ('|') md5 = hashlib. md5 () md5.update (bytes (pwd, encoding = 'utf-8') md5_pwd = md5.hexdigest () if usr = user and md5_pwd = passwd: print ('logon successful ')

# Adding salt

Import hashlib # module that provides digest algorithms md5 = hashlib. md5 (bytes ('Salt ', encoding = 'utf-8') # md5 = hashlib. md5 () md5.update (B '000000') print (md5.hexdigest ())
Add salt

# Dynamic salt adding

# Dynamically add salt # user name and password # use a part of the user name or directly use the whole user name as the salt import hashlib # provide Digest algorithm module md5 = hashlib. md5 (bytes ('yan', encoding = 'utf-8') + B ') # md5 = hashlib. md5 () md5.update (B '000000') print (md5.hexdigest ())
Dynamic salt adding

# File consistency check

Import hashlibmd5 = hashlib. md5 () md5.update (B 'alex ') md5.update (B '000000') print (md5.hexdigest () # file consistency check no need to add salt here

 

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.