use variables created in the init of a class, into staticmethod functions - python

I have a class; which in its constructor, is assigning a variable.
I want to call this variable, from a function inside this class, which is a staticmethod. I can't seem to find the right way to do this.
class myclass:
def __init__(self):
myvariable = os.cwd()
#staticmethod
def myfunction(someparameter)
print(myclass.myvariable)
print(someparameter)
When I run the class from python, I get an error that myvariable does not exist
mytestclass = myclass
myclass.myfunction("foo")
I tried to use both self.myvariable and myvariable, but it does not make any difference. I didn't use #classmethod because if I would call cls.myvariable, I would not get that specific instance of myclass; and if I have multiple instances I may end up with issues.

myVariable is only a temporary variable in this case, that only is visible in the __init__ method, not even in other methods of the class. You could use myclass.myvariable also in the __init__ method.
You can do it as follows. I also added an instance counter:
class myclass:
counter= 0
def __init__(self):
myclass.myvariable = os.cwd()
myclass.counter+= 1
#staticmethod
def myfunction(someparameter):
print(myclass.myvariable)
print(myclass.counter)
print(someparameter)

Related

Calling a variable within a class from a method in the class in Python

class a_class():
a_class_variable = 1
#classmethod
def a_class_method(cls):
print(a_class.a_class_variable)
a_variable = a_class()
a_variable.a_class_method()
I was just looking up calling a variable of a class inside a method within that class and I found it but, why is it that you need to name the class that the method is within when the method is in the same class?
Shouldn't the variable be visible to the method without doing so as the method is within the same class as the variable?
I can see this as being needed if you're calling a variable in a different class. For example b_class().
Is there some Pythonic reason for this convention?

Unresolved reference in class method

I don't think it is because of the scope of the function, but I get a
Unresolved reference at get_all_predicates(examples).count(predicate_list[0])
inside get_entropy_of_attributes(examples, predicate_list) function in my class Tree:
class Tree:
def get_examples(examples, attributes):
for value in examples:
yield dict(zip(attributes, value.strip().replace(" ", "").split(',')))
def get_all_predicates(examples):
return [d['Predicate'] for d in examples]
def get_entropy_of_attributes(examples, predicate_list):
get_all_predicates(examples).count(predicate_list[0])
return 0
examples = list(get_examples(all_examples, name_of_attributes))
predicate_list = list(set(get_all_predicates(examples)))
get_entropy_of_attributes(examples, predicate_list)
all_examples is a list of dictionary and name_of_attributes is a list, that holds values imported from a text file.
all_examples = [{'P_Length': '1.4', 'P_Width': '0.2', 'Predicate': 'I-setosa', 'Sepal_Width': '3.5', 'S_Length': '5.1'}, ...]
name_of_attributes = ["Check","P-Width"]
Any help?
Classes do not have scopes, only namespaces. This means that functions defined within them cannot see other class variables automatically.
class Foo(object):
var = 1 # lets create a class variable
def foo():
print(var) # this doesn't work!
To access a class variable, you need use attribute syntax: either Foo.var (to access via the class) or, if you're writing an instance method, with self.var (to access via the current instance, which will be passed in as the first argument).
class Bar(object):
var = 1
def bar1():
print(Bar.var) # works
def bar2(self):
print(self.var) # also works, if called on an instance, e.g. `Bar().bar2()`
With this kind of setup you can almost fix your current code (but not quite).
def get_entropy_of_attributes(examples, predicate_list):
Tree.get_all_predicates(examples).count(predicate_list[0]) # name the class
return 0
If you call this after the class is fully initialized, it will work without any exceptions (though it's implementation seems a bit nonsensical). However, it doesn't work when you call it to define a class variable, as your current code does. That's because the class object is only created and bound to the class name after all of the class body has been run.
I think the fix for that is probably to redesign your class in a more conventional way. Rather than having class variables set up based on various globals (like all_examples), you should probably create instances of your class by passing in arguments to the constructor and making the other variables you calculate from them instance attributes. I'd try to write it out, but frankly I don't understand what you're doing well enough.
If you want to call class methods, you have to call them with self, e.g.
class myClass:
def __init__(self):
pass
def get_all_predicates(self):
print('asd')
def do_something(self):
self.get_all_predicates() # working
get_all_predicates() # → Unresolved reference
test = myClass()
test.do_something()
See this link for examples for Python classes.

How to use method of one class to another class in different files in python

I am quite new to python, so pardon me for basic question. I tried google for past few days but could not make it in my program.
Can anyone show me a good example how can I use method from One class to another in python and what is significance of __init__ while defining class.
I am using python2.7
Thanks in anticipation.
To use a method defined in one class inside of another class, you have several options:
Create an instance of B from within one of A's methods, then call B's method:
class A:
def methodInA():
b = B()
b.methodInB()
If appropriate, use the concept of inheritance (one of the defining concepts of object-oriented design) to create a subclass of the original class whose method(s) you wish to use:
class B(A):
...
__init__() is a class initializer. Whenever you instantiate an object you are invoking __init__() whether or not it is explicitly defined. It's main purpose is to initialize class data members:
class C:
def __init__(self, name):
self.name = name
def printName(self):
print self.name
c = C("George")
c.printName() # outputs George
With __init__() defined, in particular with the additional argument name in this example, you are able to differentiate between would-be generically constructed instances by allowing for different initial states from instance to instance.
There are 2 issues here:
First: Using method of class A in class B, both classes in different files
class A:
def methodOfA(self):
print "method Of A"
let the above class be in file a.py Now the class B is supposed to be in b.py. Both a.py and b.py are assumed to be on the same level or in the same location. Then b.py would look like:
import a
class B:
def methodOfB(self):
print "Method of B"
a.A().methodOfA()
You can also do this by inherting A in B
import a
class B(a.A):
def methodOfB(self):
print "Method of B"
self.methodOfA()
there are several other ways to use A in B. I will leave it to you to explore.
Now to your second question. The use of __init__ in a class. __init__ is not a constructor, as popularly believed and explained above. It is, as the name suggests, an initialization function. It is called only after the object has already been constructed and it is implicitly passed the object instance as the first argument, as signified by self in its argument list.
The actual constructor in python is called __new__, which does not need a object to call it. This is actually a specialized Static method, which receives the class instance as the first argument. __new__ is exposed for overwriting only if the class inherits form the object base class of python
Whatever other arguments are passed while creating an object of a class, first go to __new__ and then are passed with the object instance to the __init__, if it accepts them.
The init function is what is called a constructor function. When you create an instance of a class object = myClass(), init is the function that is automatically called. i.e.
That being said, to call a function from one class to another, you need to call an instance of the second class inside the first one, or vice versa. for eg.
class One():
def func(self):
#does sometthing here
class Two():
def __init__(self):
self.anotherClass = One()
#Now you can access the functions of the first class by using anotherClass followed by dot operator
self.anotherClass.func()
#When you call the main class. This is the time the __init__ function is automatically called
mainClass = Two()
Another way to access from another class is the use of oop concept called Inheritance.
class One():
def __init__(self):
print('Class One Called')
def func(self):
print('func1 Called')
class Two(One):
def __init__(self):
One.__init__(self,) #This basically creates One's instance
print('Main Called')
c= Two()
c.func()
The output for this is:
Class One Called
Main Called
func1 Called

Class variable access in all class method

I want to have a class variable, so that the value can be access in all instances, but I also want to access the variable in methods inside the class. Is that possible? I have tried this, but it didn't work at all.
class myClass:
myvariable = 1
def add():
myvariable+= 1
def print1():
print myvariable
I want to make two instances, one only do add method, the other only do print1 method
Yes, just access the variable on the class object:
class myClass(object):
myvariable = 1
def add(self):
myClass.myvariable += 1
def print1(self):
print myClass.myvariable
or if you want to set it per sub-class, use type(self):
class myClass(object):
myvariable = 1
def add(self):
type(self).myvariable += 1
def print1(self):
print type(self).myvariable
The difference is that the latter will create a separate attribute on any subclass when set, masking the base class attribute. This is just like setting an attribute on an instance would mask the class attribute.
Although you can get the class attribute via self as well (print self.myvariable), explicit is better than implicit here, and avoids accidentally being masked by an instance attribute of the same name. Setting class attributes always has to be done on the class; setting it on self would create or update an instance attribute instead (not shared).
Do inherit your classes from object though; using new-style classes has many advantages, not in the least that type(self) will then actually return the class. In old-style classes (not inheriting from object) you'd have to use self.__class__ instead.
Using object as a base also gives you a third option, class methods with the #classmethod decorator; use these when you only need to access the class object, not the instance. These methods are bound to the current (sub)class, so their effect on class attributes is the same as using type(self):
class myClass(object):
myvariable = 1
#classmethod
def add(cls):
cls.myvariable += 1
#classmethod
def print1(cls):
print cls.myvariable

NameError: name 'self' is not defined - when trying to post values to different queues

is this correct way of doing.i am a newbie python
class main(threading.Thread):
queueLock = threading.Lock()
EppQueue = Queue.Queue(1)
CrQueue = Queue.Queue(1)
EPP = threading.Thread(name='EPP', target=EPP, args=(0,EppQueue,))
cr = threading.Thread(name='cr', target=CR, args=(0,CrQueue,))
EPP.setDaemon(True)
EPP.start()
Cr.start()
self.send_queue("EppQueue","sss")
self.send_queue("CrQueue","ssds")
def send_queue(self,queuename,qvalue,b=None):
if b is None:
b = self.queuename
self.queueLock.acquire()
self.b.put(qvalue)
self.queueLock.release()
when i run this i get NameError: name 'self' is not defined ???
The variable self (the first argument to a class method - you can use any name for it) is meant to refer to a class instance (also called an object). You use self where self is not defined, right out in the class where no specific object is yet known.
When the code queueLock = threading.lock() ... etc, is executed you are not in a class object (instance) but in the context of the class, so your lock will be the same for all objects of the class.
About send_queue, it's defined and known to all objects via the class, so you do not need to use self. to access it.
If you want some code to be executed at instance creation put it in __init__.
class main(threading.Thread):
def __init__(self):
self.queueLock = threading.Lock()
.. some code ...
send_queue("EppQueue","sss")
send_queue("CrQueue","ssds")
You cannot use "self" for a Class variable / function..You can use "self" for an instance of Class...
For example :
class A():
x=3
class B():
def __init__(self):
self.x=3
A.x is a class variable. B's self.x is a instance variable..!!
Also for calling a function of Class..the best practice is to make an instance (Object) of that Class and Call the function with that Object..!!
Like :
x = main()
x.send_queue()
And for code to be run on "instance" creation, put that code in
__init__(): function
Please make sure that the send_queue function is part of the main class. The self is like this pointer in C++ and needs to be associated with a class. The send_queue function should be indented along with the main class

Categories