简体   繁体   中英

Why can't I access a variable from another class Python

When I run hello printer I get this error

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

please help!

hello printer

from rpg import *
print Setup.hello

rpg

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

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()

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

You define hello in the function setup so it does not belong to the class namespace. To access a class variable you need to define it in the class, not in a function:

class Setup(object):
    hello = 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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