Calling variable inside self parameter in class method - python

I wonder if we can call variable initiated in self in class method. For example:
class ABC():
def method1(self):
self.var1 = '123'
#classmethod
def callvar1(cls):
'''print var1'''
I want to achieve the same output like this:
class ABC():
var1 = '123'
def method1(self):
self.var1 = '123'
#classmethod
def callvar1(cls):
print(cls.var1)
How can I access self.var1 in callvar1?

Since callvar1 is a class method, it does not have access to self. This is because the method is not tied to a specific instance of the class, but rather to the class itself. Therefore, when you call the method, it does not know which instance you are referring to. As you did in the second block of the code, you must pass the object whose var1 you would like to print to the function.
Your other option would be to not make it a class method.

Class methods are bound to the class itself rather than a particular instance of it so if you're trying to access self.var1 (an instance variable) inside the class method you're not going to have much fun.
Your best option is to simply make the method not a class method (depending on your use case):
>>> class ABC():
... var1 = '123'
... def method1(self):
... self.var1 = '123'
... def callvar1(self):
... print(self.var1)
...
>>> b = ABC()
>>> b.callvar1()
123
Although another option is to pass an instance of the class to the class method:
>>> class ABC():
... var1 = '123'
... def method1(self):
... self.var1 = '123'
... #classmethod
... def callvar1(cls, inst):
... print(inst.var1)
...
>>> b = ABC()
>>> ABC.callvar1(b)
123

Use the self keyword to access members of the class.
class ABC():
var1 = '123'
def method1(self):
self.var1 = '123'
#classmethod
def callvar1(self):
print(self.var1)

Related

Calling a method's variablename from class A into Class B

I have been searching an answer to my question but could not hit the related answer.
Basically i am trying to call a variable from a Class A thats actually GUI to another Class B my code goes like this:
class CLASSA(wx.Frame):
def Method(self):
self.Var = anyvalue
import CLASSA
class CLASSB():
def __init__(self):
self.Var = CLASSA().Method.Var
i have tried as above but its not working out. Isn't it possible to carry out as mentioned ?
At the very least, you need to actually call CLASSA.Method first:
class CLASSB():
def __init__(self):
self.Var = CLASSA().Method().Var
in order for the Var attribute of the CLASSA object to be initialized.
You do not give enough detail to know if Method is necessary. You could, for instance, simply initialize Var in CLASSA.__init__.
# With recommended capitalization
class A(wx.Frame):
def __init__(self):
self.var = any value
class B(object):
def __init__(self):
sef.var = A().var
It's also possible that B should be a subclass of A, in which case B simply inherits var from A:
>>> class B(A):
... pass
>>> print B().var
anyvalue

How would I access variables from one class to another?

I am writing a program that is utilizing multiple classes. I have one class that is dedicated to determining values for a set of variables. I would then like to be able to access the values of those variables with other classes. My code looks as follows:
class ClassA(object):
def __init__(self):
self.var1 = 1
self.var2 = 2
def methodA(self):
self.var1 = self.var1 + self.var2
return self.var1
class ClassB(ClassA):
def __init__(self):
self.var1 = ?
self.var2 = ?
object1 = ClassA()
sum = object1.methodA()
print sum
I use classA to initialize 2 variables (var1 and var2). I then use methodA to add them, saving the result as var1 (I think this will make var1 = 3 and var2 = 2). What I want to know is how would I have ClassB then be able to get the values for var1 and var2 from ClassA?
var1 and var2 are instance variables. That means that you have to send the instance of ClassA to ClassB in order for ClassB to access it, i.e:
class ClassA(object):
def __init__(self):
self.var1 = 1
self.var2 = 2
def methodA(self):
self.var1 = self.var1 + self.var2
return self.var1
class ClassB(ClassA):
def __init__(self, class_a):
self.var1 = class_a.var1
self.var2 = class_a.var2
object1 = ClassA()
sum = object1.methodA()
object2 = ClassB(object1)
print sum
On the other hand - if you were to use class variables, you could access var1 and var2 without sending object1 as a parameter to ClassB.
class ClassA(object):
var1 = 0
var2 = 0
def __init__(self):
ClassA.var1 = 1
ClassA.var2 = 2
def methodA(self):
ClassA.var1 = ClassA.var1 + ClassA.var2
return ClassA.var1
class ClassB(ClassA):
def __init__(self):
print ClassA.var1
print ClassA.var2
object1 = ClassA()
sum = object1.methodA()
object2 = ClassB()
print sum
Note, however, that class variables are shared among all instances of its class.
Can you explain why you want to do this?
You're playing around with instance variables/attributes which won't migrate from one class to another (they're bound not even to ClassA, but to a particular instance of ClassA that you created when you wrote ClassA()). If you want to have changes in one class show up in another, you can use class variables:
class ClassA(object):
var1 = 1
var2 = 2
#classmethod
def method(cls):
cls.var1 = cls.var1 + cls.var2
return cls.var1
In this scenario, ClassB will pick up the values on ClassA from inheritance. You can then access the class variables via ClassA.var1, ClassB.var1 or even from an instance ClassA().var1 (provided that you haven't added an instance method var1 which will be resolved before the class variable in attribute lookup.
I'd have to know a little bit more about your particular use case before I know if this is a course of action that I would actually recommend though...
var1 and var2 is an Instance variables of ClassA. Create an Instance of ClassB and when calling the methodA it will check the methodA in Child class (ClassB) first, If methodA is not present in ClassB you need to invoke the ClassA by using the super() method which will get you all the methods implemented in ClassA. Now, you can access all the methods and attributes of ClassB.
class ClassA(object):
def __init__(self):
self.var1 = 1
self.var2 = 2
def methodA(self):
self.var1 = self.var1 + self.var2
return self.var1
class ClassB(ClassA):
def __init__(self):
super().__init__()
print("var1",self.var1)
print("var2",self.var2)
object1 = ClassB()
sum = object1.methodA()
print(sum)
we can access/pass arguments/variables from one class to another class using object reference.
#Class1
class Test:
def __init__(self):
self.a = 10
self.b = 20
self.add = 0
def calc(self):
self.add = self.a+self.b
#Class 2
class Test2:
def display(self):
print('adding of two numbers: ',self.add)
#creating object for Class1
obj = Test()
#invoking calc method()
obj.calc()
#passing class1 object to class2
Test2.display(obj)
Just create the variables in a class. And then inherit from that class to access its variables. But before accessing them, the parent class has to be called to initiate the variables.
class a:
def func1(self):
a.var1 = "Stack "
class b:
def func2(self):
b.var2 = "Overflow"
class c(a,b):
def func3(self):
c.var3 = a.var1 + b.var2
print(c.var3)
a().func1()
b().func2()
c().func3()
class ClassA(object):
def __init__(self):
self.var1 = 1
self.var2 = 2
def method(self):
self.var1 = self.var1 + self.var2
return self.var1
class ClassB(ClassA):
def __init__(self):
ClassA.__init__(self)
object1 = ClassA()
sum = object1.method()
object2 = ClassB()
print sum

Setting name of variable in a class with a function?

I have a class and I want to do something like the following:
class my_class:
def my_func(self, var_name):
self.var_name = 5
a = my_class()
a.my_func('yes')
print(a.yes)
I am not sure how to set the class variable name using the function however
>>> class my_class(object):
... def my_func(self,var_name):
... setattr(self,var_name,5)
...
>>> a = my_class()
>>> a.my_func('yes')
>>> a.yes
5

python/pygame, pass input from a class to another class

there is a way to pass a value or a variable from a class to another class without having to pass through the main function
I'm using python
well, of course you can access other objects attributes in methods of a specific object. e.g:
class A(object):
def method(self, other):
other.somevar = 5
class B(object):
pass
def main():
a = A()
b = B()
b.somevar = "Hello World"
a.method(b)
print(b.somevar) # now prints '5'

python oop polymorphism

I can't understand why this code:
class A(object):
def __init__(self):
self.__value = 1
def get_value(self):
return self.__value
class B(A):
def __init__(self):
A.__init__( self )
self.__value = 2
b = B()
print b.get_value()
gives 1, but not 2. Thanks for your help.
Your problem is that double underscores are special in python, and create some modicum of privacy (not enforced, but it mangles the names, which is what is affecting you here). You should recreate this without the variable being named with double underscores. Also, you should use super instead of calling A.__init__ explicitly:
>>> class A(object):
... def __init__(self):
... self.value = 1
... def get_value(self):
... return self.value
...
>>> class B(A):
... def __init__(self):
... super(B, self).__init__()
... self.value = 2
...
>>> b = B()
>>> b.get_value()
2
For more specifics if you don't want to read the referenced documentation:
If you read the link on "special" above, that paragraph describes the internal name mangling that happens when you use __. The short answer is that A.get_value() returns _A__value, and setting self.__value in B actually sets a member variable named _B__value, which means that A.get_value() never sees it.
You can prove this to yourself by indeed doing something truly hinky:
>>> class A(object):
... def get_value(self):
... return self._B__value
...
>>> class B(A):
... def __init__(self):
... self.__value = 2
...
>>> b = B()
>>> b.get_value()
2
self.__value = 1 creates 'private' field, which is invisible for children in a such way.
Use single underscore for 'protected' fields.
E.g. self._value = 1
When you creates field with name started with double underscore, Python makes some modification on it before adding to object's __dict__:
>>> class A(object):
... def __init__(self):
... self.__value = 1
... def get_value(self):
... return self.__value
...
>>> A().__dict__
{'_A__value': 1}
That is why __value field is not visible in child object.

Categories