Acessing to global variable from class function in Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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?

Answers

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.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/21554170/acessing-to-global-variable-from-class-function-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils