top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the scope of class variables in python? Does the self prefix modify this scope?

+1 vote
296 views
What is the scope of class variables in python? Does the self prefix modify this scope?
posted Oct 19, 2015 by Parveen

Looking for an answer?  Promote on:
Facebook Share Button Twitter Share Button LinkedIn Share Button

Similar Questions
0 votes

Sorry for the vague title. Probably best to just show you the code that explains it better.

This is a simplified example of what I want to do:

# THIS DOESN'T WORK
from random import choice

class Expr(object):
 """
 Expr(expr, op, val) -> an expression object.
 """

 def __init__(self, expr, op='', val=''):
 self.expr = expr # can be another instance of Expression.
 self.op = op
 self.val = val

 def __str__(self):
 return ("%s %s %s" % (self.expr, self.op, self.val)).strip()

 def expand(self):
 self = Expr(self, choice('+-*/'), choice('12345'))

Then I tried messing around with Expr.__new__() and Expr.__init__() but that didn't work.

The only way I've got it to work is by doing the expanding part outside of the object, by a method of some other class. But I want the Expr class to be responsible for itself. How can I do this and why doesn't the above work?

+4 votes

Probably I'm turning the use of regular expressions upside down with this question. I don't want to write a regex that matches prefixes of other strings, I know how to do that. I want to generate a regex -- given another regex --, that matches all possible strings that are a prefix of a string that matches the given regex.

E.g. You have the regex ^[a-z]*4R$ then the strings "a", "ab", "A4" "ab4" are prefixes of this regex (because there is a way of adding characters that causes the regex to match), but "4a" or "a44" or not.
How do I programmatically create a regex that matches "a", "ab", "A4", etc.. but not "4a", "a44", etc..

Logically, I'd think it should be possible by running the input string against the state machine that the given regex describes, and if at some point all the input characters are consumed, it's a match. (We don't have to run the regex until the end.) But I cannot find any library that does it...

+3 votes

Sometimes python shell throws error while declaring variables . Is there any single place where all the rules are defined ?

+3 votes

Is there way to get list of instances of particular class through class itself? via metaclass or any other method?

If class is object is it possible to delete it? If it is possible then how instances of that class will behave?

...