Hi everyone i wanna use a calculated value from a method of the class itself for the rest of the class methods but it must calculate once for all and i need to invoke method inside the class itself i write an example:
class something():
def __init__():
pass
def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)
# I need to calculate summation here once for all:
# how does the syntax look likes, which one of these are correct:
something.__sum(1, 2)
self.__sum(1, 2)
# If none of these are correct so what the correct form is?
# For example print calculated value here in this method:
def do_something_with_summation(self):
print(self.summation)
Something like this seems to be what you're looking for:
class Something:
def __init__(self):
self.__sum(1, 2)
def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)
Not saying this is the ideal approach or anything, but you haven't really given us much to go off of.
In general, make sure self is the first argument in all class methods, and you can call that class method at any time using either self.method_name() if you are using it from within another class method or instance.method_name() if you're using it externally (where instance = Something()).
Assuming that you would receive variable1 and variable2 when you instantiate the class one solution could be:
class something():
def __init__(self, variable1, variable2):
self.summation = variable1 + variable2
def do_something_with_summation(self):
print(self.summation)
If instead you're creating variable1 and variable2 inside other methods, then you could make them class variables:
class Something():
def __init__(self):
#Put some initialization code here
def some_other_method(self):
self.variable1 = something
self.variable2 = something
def sum(self):
try:
self.summation = self.variable1 + self.variable2
except:
#Catch your exception here, for example in case some_other_method was not called yet
def do_something_with_summation(self):
print(self.summation)
Related
I have a python function:
class MyClass:
my_class_variable: str = Optional[None]
#classmethod
def initialize(cls):
cls.my_class_variable = cls.some_function()
I plan to use it like:
x = MyClass.my_class_variable
How can I guarantee have my_class_variable to have initialized with a value, eg how can I force call initialize() ?
you could do something like :
def dec(cls):
cls.my_class_var = cls.some_func()
return cls
#dec
class MyClass:
my_class_var = ""
#classmethod
def some_func(cls):
return "Cool :)"
print(MyClass.my_class_var) --> Cool :)
Another option would be to use a metaprogramming, but as long as there is only one simple thing to do, I would use a decorator :)
How do I use the function in the class below in the other class without using global?
Code:
class one:
class one_one:
def add(x):
return x+1
class one_two:
ans = one.one_one.add(1)
It certainly is an unusual design, but it will work if you remember to distinguish between classes and instances of classes (objects). In your example you are attempting to call add in the class one_one which is an instance method without first instantiating an object of that class type. The example below shows one way to achieve what you are trying to do by instantiating the objects before calling their methods.
Example:
class one:
class one_one:
def add(self, x):
return x+1
class one_two:
def add(self):
a_one_one = one.one_one()
ans = a_one_one.add(1)
return ans
a_one_two = one.one_two()
print(a_one_two.add())
Output:
2
Here is some example code for the question:
class Obj():
def __init__(self, p):
self.property = p
def printProp(self):
print(self.property)
myVar = 0
myObject = Obj(myVar)
myObject.printProp()
myVar = 1
myObject.printProp()
When this runs, the parameter is not changed, and 0 is printed twice, because the constructor is only called once. Is there a way to have the property always directly reference the myVar variable?
You can access the classes property directly like this: myObject.property = 1.
Alternatively, you could add a class method to set the property like this:
def setProp(self, val):
self.property = val
This is generally better coding practice as class properties should only be modified within the class.
I have a model where I want to use a class method to set the default of for a property:
class Organisation(db.Model):
name=db.StringProperty()
code=db.StringProperty(default=generate_code())
#classmethod
def generate_code(cls):
import random
codeChars='ABCDEF0123456789'
while True: # Make sure code is unique
code=random.choice(codeChars)+random.choice(codeChars)+\
random.choice(codeChars)+random.choice(codeChars)
if not cls.all().filter('code = ',code).get(keys_only=True):
return code
But I get a NameError:
NameError: name 'generate_code' is not defined
How can I access generate_code()?
As I said in a comment, I would use a classmethod to act as a factory and always create you entity through there. It keeps things simpler and no nasty hooks to get the behaviour you want.
Here is a quick example.
class Organisation(db.Model):
name=db.StringProperty()
code=db.StringProperty()
#classmethod
def generate_code(cls):
import random
codeChars='ABCDEF0123456789'
while True: # Make sure code is unique
code=random.choice(codeChars)+random.choice(codeChars)+\
random.choice(codeChars)+random.choice(codeChars)
if not cls.all().filter('code = ',code).get(keys_only=True):
return code
#classmethod
def make_organisation(cls,*args,**kwargs):
new_org = cls(*args,**kwargs)
new_org.code = cls.generate_code()
return new_org
import random
class Test(object):
def __new__(cls):
cls.my_attr = cls.get_code()
return super(Test, cls).__new__(cls)
#classmethod
def get_code(cls):
return random.randrange(10)
t = Test()
print t.my_attr
You need specify the class name: Organisation.generate_code()
I am pretty new to Python world and trying to learn it.
This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :)
class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
def showName():
print carName
a = Car("bmw")
a.showName()
derived from object for new-style class
use __init__ to initialize the new instance, not __self__
__main__ is helpful too.
class Car(object):
def __init__(self,input):
self.carName = input
def showName(self):
print self.carName
def main():
a = Car("bmw")
a.showName()
if __name__ == "__main__":
main()
You don't define a variable, and you use init and self.
Like this:
class Car(Object):
def __init__(self,input):
self.carName = input
def showName(self):
print self.carName
a = Car("bmw")
a.showName()
this is not correct!
class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
the first carName is a class Variable like static member in c++
the second carName (self.carName) is an instance variable,
if you want to set the class variable with the constructor you have to do it like this:
class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
Car.carName = input