Python说文解字_杂谈08

 1. Python变量到底是什么?

  Python和Java中的变量本质不一样,python的变量实质是一个指针 int str,便利贴

  a = 1

  # 1. a贴在1上面

  # 2. 它的过程是先生成对象,然后贴便利贴。

  # 3. is 是指的标签贴是否一样。

  a = 1

  b = 1 

  这个是一样,用的是小整数的内部inter机制的内部优化。

  == 用的是__eq__这个魔法函数。

  # 4. 常用的用法是isinstance或者type() is,这两种是通用的。type实际上是指向了这个对象的。

 

2. del语句和垃圾回收的关系:

  py中的垃圾回收采用的是引用计数。

# a = 1
# b = a
# del a # 引用计数器减去1,等于0的时候py会回收。

a = object()
b = a
del a
print(b) # b可以打印,a打印不出来了
print(a)

# C:\Python37\python.exe F:/QUANT/练习/chapter01/type_object_class.py
# Traceback (most recent call last):
#   File "F:/QUANT/练习/chapter01/type_object_class.py", line 9, in <module>
#     print(a)
# NameError: name 'a' is not defined
# <object object at 0x000002909F4AAA70>
#
# Process finished with exit code 1

class A:
    del __del__(self):
        pass

  记住:对应的魔法函数是__del__

 

3. 默认空的list的可变,一个景点的参数传递问题。

def add(a,b):
    a += b
    return a
class Company:
    def __init__(self,name,staffs=[]):
        self.name = name
        self.staffs = staffs

    def add(self,staff_name):
        self.staffs.append(staff_name)

    def remove(self,staff_name):
        self.staffs.remove(staff_name)

if __name__ == '__main__':
    # a = 1
    # b = 2
    # c = add(a,b)
    # print(c)
    # print(a,b)
    # 3
    # 1 2

    # a = [1,2]
    # b = [3,4]
    # c = add(a,b)
    # print(c)
    # print(a,b)
    # [1, 2, 3, 4]
    # [1, 2, 3, 4][3, 4]

    # a = (1,2)
    # b = (3,4)
    # c = add(a,b)
    # print(c)
    # print(a,b)
    # (1, 2, 3, 4)
    # (1, 2) (3, 4)

    com1 = Company("con1",["bobby1","bobby2"])
    com1.add("bobby3")
    com1.remove("bobby1")
    print(com1.staffs)
    # ['bobby2', 'bobby3']

    com2 = Company("com2")
    com2.add("bobby")
    print(com2.staffs)
    # ['bobby']


    com3 = Company("com3")
    com3.add("bobby5")
    print(com2.staffs,com3.staffs)
    # ['bobby', 'bobby5']['bobby', 'bobby5']

    print(com2.staffs is com3.staffs)
    # True

    # 这个原因是运用了一个可变对象=[]
    print(Company.__init__.__defaults__)

  记住:在类中可变对象的话容易造成错误的,把a就行修改掉了。

  记住:其实这里就是引用参数的问题。引用参数是用可变对象来实现的。

 

posted @ 2019-06-08 13:51  时海涛|Thomas  阅读(142)  评论(0编辑  收藏  举报