Some methods function object

A custom comparison __gt__ greater than, __ lt__ less than, __ eq__ equal

These three custom may be utilized for comparison:
gt : Greater Within last greater than abbreviations
lt : Abbreviation less Within last less than
EQ : equal equal Acronym

class Student(object):
    def __init__(self, name, height, age):
        self.name = name
        self.height = height
        self.age = age

    # 比较大于时触发
    def __gt__(self, other):
        return self.height > other.height

    # 比较小于时触发
    def __lt__(self, other):
        return self.age < other.age

    # 比较等于时触发
    def __eq__(self, other):
        # if self.age == other.age:  # 比较两个对象的年龄
        if self.age == other.age and self.height == other.height:  # 比较年龄和身高
            return '年龄身高一样'
        return '年龄身高不一样'


stu1 = Student("jeff", 170, 25)
stu2 = Student("make", 170, 25)

print(stu1 > stu2)
print(stu1 < stu2)
print(stu1 == stu2)

Second, the context management __enter__ into the file, __ exit__ leave

the Enter :. 1 into the file, perform a war file
2. The function should return to their Self
Exit :. 1 exit the file, an error interrupt, or executing code execution finished
2 may have a return value is of type bool

class MyOpen(object):
    def __init__(self, path):
        self.path = path
    
    # 进入文件时触发
    def __enter__(self):
        self.file = open(self.path)
        print("文件打开....")
        return self
    
    # 离开文件时触发
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("文件关闭")
        # print(exc_type,exc_val,exc_tb)
        self.file.close()  # 关闭文件
        return True


with MyOpen('a.txt') as f:
    print(f.file.readline())

# f.file.readline()   # 文件已经关闭了,不能读

Third, __ trigger str__ turn triggered when deleting a string __del__

str : string trigger again when the conversion, the conversion result is the function's return value
usage scenarios: Using this function custom print formats
del :
Execution timing: manually deleted immediately executed, or run a program automatically executed at the end
usage scenarios: when your use of the object, open the resource does not belong to the interpreter; for example, files, network ports

1 .__ str__ example:

1.# __str__例子:
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        # 自定义打印输出
        return "这是一个person对象 name:%s age:%s" % (self.name, self.age)


p = Person("jack", 20)
print(p)
  1. __del__ example:

2.# __del__例子:
class A:
    def __init__(self, name):
        self.name = name

    def __del__(self):
        print('删除时触发')

    # 删除时关闭
    def __del__(self):
        self.file.close()


jeff = A('jeff')
del jeff
# jeff.name  # 已经删除,无法访问了

Fourth, the anonymous function

Anonymous function lambda: functions without a name
Features:
temporary presence, used to destroy
an anonymous function not normally used alone or in conjunction with the built-in functions

lambda x,y : x+y

Explanation: parameter function corresponding to left, right corresponding to the return value of the function

1. The common method of summation

def my_sum(x, y):
    return print(x+y)
my_sum(1, 2)

img

2. anonymous function with built-in summation:

res = (lambda x, y: x+y)(11, 20)
print(res)

img

II: Comparison of salaries, return names:

k = {'jeff': 8000,
     'nick': 1000,
     'tank': 3000,
     'mary': 10000,
def index(name):

  return k[name]
  print(max(k, key=index)) # 函数返回什么比较什么


# max内置函数,第一步:拿到字典key(jeff)
                第二步,把key传给index函数
                第三步,执行index(jeff),返回字典k[jeff],5000
                第四步,依次拿到5000,1000,3000,10000,进行比较
                第五步,返回最大值对应的人名
"""
 

img

2. The index written anonymous function:

print(max(k, key=lambda name: k[name]))
print(min(k, key=lambda name: k[name]))

img

Third, the supplement ascll code table:

"""
A-Z 65-90
a-z 97-122
"""
print(chr(122)) #查看ascll码对应的值

img

V. package

Package: There are many tools for users to call

As a designer bag and said:

  1. When a particularly large number of functional modules, it should document management

  Between each module 2. In order to avoid problems later renamed, should relative import

Standing package developers If you use an absolute path to manage their own modules that it only takes forever to route packets as a reference

(*****) standing package user package must be located in the folder path to the system path environment variable

If you want to import the following python2 bags are not allowed to have a __init__.py file, otherwise an error

If you want to import the bag below python3 no __init__.py files are not being given

Sixth, private property, private methods

Private property, private methods:

1. Have some key data into a more private security
2. can not arbitrarily change

3. In front of the property, and methods plus '__' into private, so the outside world will not be able to call directly modified.

4. But: internal class can define a function, method call modification, the user can directly call up this function. This function is the interface
5. The conditions can be applied in this function, method, rather than any change

** Note: The reason private tune changed after less than outside is, python change the name of the private methods, read: _ __ class name method name

class student:

    def __init__(self, name, max):
        self.name = name
        self.__max = max  # 变私有
   def max(self, new_max):
        if new_max < 300:  # 条件
            print('修改成功')
            self.__max = new_max
            print(self.__max)
        else:

            print('修改失败')
jeff =student('jeff',100)  # 定义的初始

jeff.max(200)  # 外部调用接口修改,接口调用内部初始修改

结果:修改成功  200

jeff =student('jeff',100)
jeff.max(500)

结果: 修改失败  

Seven, __ slots__ optimize memory objects

slots: principle, subject to declaration only certain attributes to delete unnecessary memory, you can not add new properties
1. Optimized Object Memory
Limit the number of attributes

1 .__ slots__ Case: slots use

import sys
class Person:
    __slots__ = ['name']  # 声明名称空间只有name属性

    def __init__(self, name):
        self.name = name
p = Person('jeff')
print(sys.getsizeof(p))
#结果:48          #####内存减少了8

Guess you like

Origin www.cnblogs.com/guyouyin123/p/11346665.html