0

I want to get a variable which can be used at any method from any class.

I started like this:

class clasificadorDeTweet:

    """Funciones para clasificar tweets"""
    def fx():
        print trendingTopics

def iniciarConjuntoTrendingTopics():

    trendingTopics = ['EPN', 'PRI', 'Peña Nieto', 'México', 'PresidenciaMX', 'Osorio Chong', 'SEDENA', 'PEMEX', 'Reforma Energética', 'Guerra contra el narco', 'Reforma Fiscal', 'Los Pinos'];
    return set(trendingTopics)

global trendingTopics 
trendingTopics = iniciarConjuntoTrendingTopics()

x=clasificadorDeTweet()
x.fx

But I'm not getting anything printed. What have I got wrong?

4
  • x.fx is not a function call; you're not executing your fx function Commented Feb 4, 2014 at 13:44
  • You did not call the method: x.fx(). Commented Feb 4, 2014 at 13:45
  • 2
    You should define fx as def fx(self):. Methods require an explicit self parameter to indicate the instance. Commented Feb 4, 2014 at 13:45
  • You quite got it @Bakuriu. You should prompt and answer Commented Feb 4, 2014 at 13:47

2 Answers 2

1

You need to call the method x.fx by adding () after it:

x.fx()

However, this isn't your only problem; fx is an instance method, so it needs to take self (by convention; you can call it anything you want, but you need to have some parameter) as the first parameter.

You probably also want to use unicode strings in trendingTopics and declare a source encoding at the start of your file; embedding non-ASCII strs in your code may coincidentally work perfectly fine, then break horribly when moved to another system.

Your global statement at the module level also does literally nothing at all. Variables assigned at the module scope are already globals.

Sign up to request clarification or add additional context in comments.

3 Comments

When should I use global then? When I perform assignments to such variable names?
global lets you rebind the name globally from within some other scope. But you "should" use it pretty much never; using globals is generally a bad practice because it makes it harder to reason about code.
I got #!/usr/bin/env python # -- coding: utf-8 -- As begin of my code, is that right?
0

If you want acces to trendingTopics, you have to declare trendingTopics as global on the method scope

def fx(): global tredingTopics print tredingTopics

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.