用python调用同一类中的变量 [英] Calling variables in the same class with python

查看:134
本文介绍了用python调用同一类中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在同一类的另一个函数内调用一个函数中定义的变量,但使用 self 不起作用。

I am trying to call a variable defined in a function, inside another function of the same class, but with self doesn't work.

class Project():
    def function1(self):
        a='hello world,'

    def function2(self):
        b=self.a + ' I am alive'

Project1=Project()
print Project1.function1()
print Project1.function2()

python说:项目实例没有属性'a'

我不太清楚如何使用类。我没有使用 __ init __ ,因为我没有什么可放的,即使我不正式需要它也可以添加它吗?

I don't know very well how to use classes. I didn't use __init__ 'cause I do not have anything to put, is there maybe a way to add it even if I do not need it formally?

感谢您的帮助。

推荐答案

您的 a b 变量是局部变量。您只能在方法范围内使用这些变量。如果您想要一个类属性(与所有类共享),则必须设置 self.a = ... self.b = ...
无需在python中创建构造函数方法 __ init __ 都不初始化这些属性。
但是在您的示例中,如果您在 function1 之前调用 functions2 ,它将崩溃,因为您使用的是不存在。然后建议初始化属性。
您可以像这样初始化属性:

Your a and b variables are local. You can only use these variables in the method scope. If you want a class attribute (shared with all the class) you have to set the like self.a = ... and self.b = .... In python is not necessary create a constructor method __init__ neither initialize these attributes. But in your example if you call functions2 before function1 it will crash because you are using one attribute that doen't exist. Then is recommended initialize the attributes. You can initialize the attributes like this:

class Project:
    a = ''
    b = ''

    def function1(self):
        self.a='hello world,'

    def function2(self):
        self.b=self.a + ' I am alive'

需要记住的更多事项:

1.变量使用小写字母和蛇形字母: project1 = Project()

2。您的打印内容不会打印任何内容,因为您的函数不会返回任何内容。您必须返回以下内容:

More things to keep in mind:
1. The variables are in lower case and snake case: project1 = Project()
2. Your prints won't print anything because your functions don't return anything. You have to return something like:

def function1():
    return 'hello world,'

或者如果需要设置a并打印:

or if you need to set a and print:

def function1():
    self.a = 'hello world,'
    return self.a

这篇关于用python调用同一类中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆