python传递的值还是引用(即改变返回值或者参数值,是否影响本身)

Python参数传递采用的是“传对象引用”的方式。这种方式相当于传值和传引用的一种综合。
如果函数收到的是一个可变对象(比如字典或者列表或者类)的引用,就能修改对象的原始值--相当于通过“传引用”来传递对象。
如果函数收到的是一个不可变对象(比如数字、字符串或者元组)的引用,就不能直接修改原始对象--相当于通过“传值'来传递对象。
概念:浅拷贝与深拷贝,copy.copy(),copy.deepcopy()
测试代码

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
import torchvision
import torchvision.transforms as tf
import os
from torch.utils.data import DataLoader
from torchsummary import summary
import matplotlib.pyplot as plt
class Site():
    def __init__(self):
        self.title = 'jb51 js code'
        self.url = 'https://www.jb51.net'
    def list_all_member(self):
        print(getattr(self,"title"))
        for name,value in vars(self).items():
            print('%s=%s'%(name,value))
    def test(self):
        print(getattr(self,"title"))
        t = getattr(self,"title")
        t = "lsdak;f"
        print(getattr(self,"title"))
class LeNet(nn.Module):
    def __init__(self):
        super(LeNet, self).__init__()
        self.layer1=nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5, stride=1, padding=0)
    def test(self):
        print(self.layer1.weight.data)
        module = getattr(self,"layer1")
        print(type(module))
        print(module.weight.data)
        module.weight.data = module.weight.data*255
        print(module.weight.data)
        print(self.layer1.weight.data)
#site = Site()
#site.list_all_member()
#site.test()
net = LeNet()
net.test()

链接:https://www.jianshu.com/p/fe26afef8c8e

posted @ 2023-02-02 00:27  心比天高xzh  阅读(32)  评论(0)    收藏  举报