为什么我不能从另一个 Python 类访问变量 [英] Why can't I access a variable from another class Python

查看:47
本文介绍了为什么我不能从另一个 Python 类访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行 hello 打印机时出现此错误

When I run hello printer I get this error

AttributeError: 类型对象Setup"没有属性hello"

AttributeError: type object 'Setup' has no attribute 'hello'

请帮忙!

你好打印机

from rpg import *
print Setup.hello

角色扮演

class Setup(object):
   def setup(self):
       hello = 5

推荐答案

要么使 setup 方法成为静态,要么插入 self 参数.

Either make setup method static or insert self argument.

class Setup(object):
    @staticmethod
    def setup():
        hello = 5
        print hello
Setup.setup()

作为一个静态方法,你不必初始化一个类.或

As its a static method, you don't have to initialize a class. or

class Setup(object):
    def setup(self):
        hello = 5
        print hello
s = Setup()
s.setup()

在这种情况下,您将必须创建一个 Setup 类的对象,因为您将访问该类方法.

In this case you will have to create an object of Setup class as you will be accessing the class method.

这篇关于为什么我不能从另一个 Python 类访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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