开发者

Global variabless in Python

How can I create variables that all the methods in the class will share (fields or glob开发者_开发百科al vars)?

Another question: what is the meaning of ";" in python?


You need to provide more detail to get more meaningful answers.

There are several ways to make a variable available to the methods of a class;

Instance variable: defined in the scope of the current class instance. Commonly created with __init__(), i.e. when the instance is initiated.

class SomeClass(object):
    def __init__(self):
        self.greeting = 'Hello'
    def greet(self, name):
        return self.greeting + name

Class variable: defined in the class definition. Shared between instances

class SomeClass(object):
    greeting = 'Hello'
    def greet(self, name):
        return self.greeting + name

Note that self.greeting references the class variable greeting via the instance. Assigning to self.greeting does not change the class variable but rather overwrites the greeting instance attribute with the new value. A more explicit, perhaps clearer way of accessing the class variable is self.__class__.greeting

Module (global) variable: defined in the top-level, usually the module.

Define the variable outside the class definition and reference it within your class functions.

greeting = 'Hello'

class SomeClass(object):
    def greet(self, name):
        return greeting + name

There are all sorts of reasons why this is not often a good idea. Search Stackoverflow for 'python globals' and you'll find many explanations about why, as well as cases where it might be appropriate.


Answering "Another question"

';' (semicolon) is a statement separator. The Python Grammar defines a simple_stmt as

simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE

A trivial example:

>>> a=1; b=2; c=3
>>> a,b,c
(1, 2, 3)
>>> 


If you define a variable outside of any function or class, it is available to all the functions and classes within that file. For example:

message="Hello, world"
def speak():
    print message

By default, these variables are read-only. You can't modify message from within speak unless you specifically mark that variable as global:

message="Hello, world"
def speak():
    global message
    message = "hello, python!"
    print message

As for your other question, semicolon is a statement separator:

message="Hello, world" ; print message

It is rarely used, as there's rarely ever a compelling reason to put two statements on a single line.

In the above, the global instance of message will be changed after speak() is called.


Maybe like this.

class A:
    x = 0
    def inc(self):
        self.__class__.x += 1

b = A()
b.inc()  # A.x == 1, b.x == 1
c = A()  
c.inc()  # A.x == 2, c.x == 2

; is logic line wrap for python, it is not recommended, as it make code difficult to read.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜