如何在一个类中进行函数变量的引用

小新新dd 2020-09-10 03:55:14
class Testdd():

def out(self):
global md
md =100
print("out函数")

def other(self):
print("othoer函数")

ss = md+ 200
print(ss)

if __name__ =="__main__":
t = Testdd()
t.other()

代码如上,执行报NameError: name 'md' is not defined
我想要的结果是最后打印出300,
就是在out函数中的变量md,可以直接在other函数中使用,有什么办法可以做到吗,
我查了global说的可以,我使用缺报没有定义,求大佬的办法,谢谢了
...全文
318 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
小新新dd 2020-09-21
  • 打赏
  • 举报
回复
引用 4 楼 庸了个白 的回复:
你非要这么写也可以,办法多得是,太丑了。

class Testdd():

    def out(self):
        globals()['md'] = 100
        print("out函数")

    def other(self):
        print("othoer函数")

        ss = md+ 200
        print(ss)

if __name__ =="__main__":
    t = Testdd()
    t.other()
引用 4 楼 庸了个白 的回复:
你非要这么写也可以,办法多得是,太丑了。

class Testdd():

    def out(self):
        globals()['md'] = 100
        print("out函数")

    def other(self):
        print("othoer函数")

        ss = md+ 200
        print(ss)

if __name__ =="__main__":
    t = Testdd()
    t.other()
大哥,我复制你这个也是在报 NameError: name 'md' is not defined 这个错啊
庸了个白 2020-09-21
  • 打赏
  • 举报
回复
代码都不看,out都没调用,肯定没有啊。这么明显了。 t = Testdd() t.out() t.other()
庸了个白 2020-09-14
  • 打赏
  • 举报
回复
你非要这么写也可以,办法多得是,太丑了。

class Testdd():

    def out(self):
        globals()['md'] = 100
        print("out函数")

    def other(self):
        print("othoer函数")

        ss = md+ 200
        print(ss)

if __name__ =="__main__":
    t = Testdd()
    t.other()
庸了个白 2020-09-14
  • 打赏
  • 举报
回复
怎么不对了,global md 是超全局变量,需要在类之外有md,那么你在global就可以对md进行修改,跟你定义没有半毛钱关系 整一个类空间,最外层的变量称之为类属性,以下有三种几种写法: class A: md = xxx class B: def out(self): self.md = xxx class C: def __init__(self): self.md = xxx 在类作用域中,属性就是它的全局变量。在类的函数中,可以用上面三种方法来使用,在任何其他函数的使用都是 self.xxx
小新新dd 2020-09-14
  • 打赏
  • 举报
回复
引用 1 楼 庸了个白 的回复:

    md = 100

    def other(self):
        print("othoer函数")
        ss = self.md + 200
        print(ss)
你这个不对啊,我只是举例,想要的方式是从一个函数里定义个变量,在另一个函数中使用
庸了个白 2020-09-10
  • 打赏
  • 举报
回复

    md = 100

    def other(self):
        print("othoer函数")
        ss = self.md + 200
        print(ss)

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧