简体   繁体   English

如何访问模块中类方法内的本地对象?

[英]How to access a local object inside a class method in a module?

I was trying to access a local variable inside of a class that is in a module.我试图访问模块中类中的局部变量。 So Far I can only access it while doing the call inside the module itself and not as a import.到目前为止,我只能在模块本身内部调用时访问它,而不是作为导入。

this is my only successfull attempt to retrieve "coisa".这是我唯一一次成功检索“coisa”的尝试。 is there a easyer way to call it?有没有更简单的方法来调用它?

class Hello():
    def MyObject():
        coisa = 22
        return coisa

link = Hello.MyObject()
print(link)

But this is the situation I am trying to actually overcome.但这就是我试图真正克服的情况。 Importing a module and access a object inside it class and function.导入模块并访问其中的类和函数的对象。 Main.py主文件

import Module

link = Module.Hello.MyObject()
print(link)

Module.py模块.py

coisa = "67"
class Hello():
    def MyObject():
        coisa = "22"
        return coisa

You cannot acces coisa var directly if it is defined in your function as it is a local variable.如果coisa var 在函数中定义,则不能直接访问它,因为它是局部变量。

In an hypothetic case where coisa would be defined outside your function, you could access it directly.coisa将在您的函数之外定义的假设情况下,您可以直接访问它。 For example :例如 :

Module.py模块.py

COISA = "67"

class Hello():
    def MyObject():
        coisa = "22"
        return coisa

You can access COISA from your external code by calling it directly.您可以通过直接调用外部代码来访问 COISA。 Note the Uppercase naming style, conforming to PEP-8 naming convention for constants.请注意大写命名风格,符合​​ PEP-8 常量命名约定。

import Module

link = Module.COISA 
print(link) # Will print 67

Or you can access coisa, defined locally in your function, in Lowercase naming style, this way.或者,您可以通过这种方式以小写命名样式访问在函数中本地定义的 coisa。 You have to return the variable value in your function as it is a local variable for your function.您必须在函数中返回变量值,因为它是函数的局部变量。

import Module

link = Module.Hello.MyObject()
print(link) # Will print 22

EDIT编辑

Note that you can also directly access to a variable defined in your class.请注意,您还可以直接访问类中定义的变量。 For example :例如 :

Module.py模块.py

COISA = "67"

class Hello():

    coisa_in_my_class = "85"

    def MyObject():
        coisa = "22"
        return coisa

You can call coisa_in_my_class easily :您可以轻松调用coisa_in_my_class

import Module

link = Module.Hello.coisa_in_my_class
print(link) # Will print 85

I don't really understand the question but I think you mean a staticmethod so try this我不太明白这个问题,但我认为你的意思是staticmethod所以试试这个

class Hello():
    @staticmethod
    def MyObject():
        coisa = "22"
        return coisa

Then you can然后你可以

import Module

link = Module.Hello.MyObject()
print(link)  # 22

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM