Inside class access to outside class variable? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have classes: C1 and C2, a C1 instance is created inside C2, and some C1 class functions also need variables from C2. Although I can move those function inside C2, it would be a little bit messy. Is there any way to import C2's variable into the test_func in C1?
C1_class.py:
class C1():
C1_a = 1
C1_b = 2
def test_func(self):
result = self.C1_a*C2.C2_a+self.C1_b*C2.C2_b
return result
C2_class.py
import C1
class C2():
C2_a = 1
C2_b = 2
C1_sample = C1_class.C1()
C2_sample = C2()
print(C2_sample.C1_sample.test_func)

Printing the function isn't what you want, I think ... you want the functional value, correct?
print(C2_sample.C1_sample.test_func() )
# ^^ forgot the parentheses
Output:
5
The problem is not that they're in two different files. It's that you haven't called the function.
test_func
is the function descriptor, giving you access to that object.
It's attributes include the parameters, etc.
test_func()
is a call to the function, returning a value.

Related

Sum of items of a class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed yesterday.
Improve this question
What I have to do is to create a class that counts from a giving single argument and itself make the arithmetical operation.
class Counts:
def __init__(self, value=0):
self.value = value
def newvalue(self, other):
return Counts(self.value + other)
But for every I make to the code I got any different error, either syntax or callable argument.
The idea is to get
Counts()
Expected output
0
Next
Counts.newvalue(10)
Expected output
10
Next
Counts.newvalue(40)
Expected output
50
Next
Counts.newvalue(-17)
Expected output
33
And so on.
The code that shows the expected behaviour is
class Counts:
value = 0
def __new__(self):
return self.value
#classmethod
def newvalue(cls, other):
cls.value += other
return cls.value
however this is a somewhat strange piece of code, as you are creating a class that returns a value when initialized instead of an object deriving from that class by overriding __new__, which is pretty non-standard.
also if you want to zero the value whenever Count() is called, you can add a self.value = 0 before the return self.value
Tests ->
print(Counts())
print(Counts.newvalue(10))
print(Counts.newvalue(40))
print(Counts.newvalue(-17))
returns
0
10
50
33

Best practice to create a python class that manage an object list and how to include in UML diagram [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am trying to improve my object oriented programming skills. So I did this practice in python in which I try to create a cake object. However I have a doubt as to whether I am doing things correctly.
I need this class handle a list of ingredients.For this I created an empty list and a method that receives as a parameter an Ingredent object instance.
#Define a ingredient.
class Ingredient:
#Constructor of ingredient
def __init__(self, name,measure):
#Name of ingredient
self.name = name
#unit of measurement
self.measure = measure
class IngredientQuantity(Ingredient):
def __init__(self,name,measure,quantity):
'''
Here we are having access to methods and attributes from
the parent class. Now we can set attribute values and access to
methods.
'''
super().__init__(name,measure)
#Define quantity of ingredient.
self.quantity = quantity
#Define a list of ingredients.
class IngredentsList:
def __init__(self):
#Empty list that will be populated with ingredients.
self.listOfIngredients = []
#Add a new ingredient to list.
def addIngredent(self,ingredient):
print('adding ' + str(ingredient.quantity) + ' ' + ingredient.measure + ' of ' + ingredient.name + '...')
self.listOfIngredients.append(ingredient)
Here is how I pass parameters...
ilist = IngredentsList()
ilist.addIngredent(IngredientQuantity('ingredient','piece',1))
I'm not sure this is the best way to do it. Then I would like to hear an opinion.
I also have doubts about how to treat this class in a UML diagram. This class is not inherited from any other. How could I relate it?
Thanks in advance.
An ingredient is just a string. Doesn't need a class.
A measurement, on the otherhand includes a unit and a quantity (e.g. 2 TBSP). So, create a class for that
from dataclasses import dataclass
#dataclass
class Measurement:
unit: str
quantity: float
Then you want to store a list of ingredients with measurements, so you can use a list of tuples
recipe = [
('Apples', Measurement(None, 1.0))
('Cinnamon', Measurement('tbsp', 2.0))
]
If you really wanted to create other classes, you could, but the relationships as far as UML goes is composition and aggregation, not inheritance.

"def" bringing the wrong answer [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I made a class with some functions:
But when I instantiate the values the answer is bringing me 'alimentos', but that's wrong it should be 'portugues' .
I have two dictionaries and this class:
professores_x = {
'alimentos': [{"prof_id":"xx_alimento_1", "prof_disc":"alimentos"},
{"prof_id":"xx_alimento_2", "prof_disc":"alimentos"}],
'português': [{"prof_id":"xx_port_1", "prof_disc":"português"},
{"prof_id":"xx_port_2", "prof_disc":"português"}]}
courses_x = {'alimentos': [{"course_name":"padeiro_confeiteiro"},
{"course_name":"padeiro_confeiteiro"}]}
# trying refactoring
class Disciplinas_cursos_1:
"Define the disciplinas and professors"
def __init__(self,cursos_,professores_):
self.cursos_ = cursos_
self.professores_ = professores_
for self.p in self.cursos_.keys():
if self.p == 'alimentos': self.alimentos()
elif self.p == 'português': self.portugues()
def alimentos(self):
profiel_prof_disc = self.professores_[self.p][::]
prof_disc_al = self.p
discipl_alimentos = [self.p,[x['prof_id'] for x in profiel_prof_disc
if x['prof_disc'] == prof_disc_al]]
return discipl_alimentos
def portugues(self):
print("Now its portuguese turn")
profiel_prof_disc = self.professores_[self.p][::]
prof_disc_port = self.p
print(f"see I'm printing {prof_disc_port}. It's that the same of portuguese? If' not it's wrong")
discipl_port =[self.p,[x['prof_id'] for x in profiel_prof_disc if x['prof_disc'] ==prof_disc_port]]
print(f"see I'm printing {prof_disc_port} and {discipl_port}")
return discipl_port
# ok!! Now I do the instance:
disc_a = Disciplinas_cursos_1(courses_x, professores_x)
disc_a.alimentos()
Output
['alimentos', ['xx_alimento_1', 'xx_alimento_2']]
Nice, that is what I want but when I try the second function it's bring me 'alimentos'
but I need 'portugues' and not 'alimentos'.
disc_a.portugues()
Output
Now its portuguese turn
see I'm printing alimentos. It's that the same of portuguese? If' not it's wrong
see I'm printing alimentos and ['alimentos', ['xx_alimento_1', 'xx_alimento_2']]
Your issue is with self.p. In __init__, you're setting that value with your loop, and when you call self.alimentos() or self.portugues() in the body of the loop it will make sense since the self.p value will correspond to the method being called.
But if you call disc_a.portugues() from outside of __init__, you're going to get the last value self.p had after the loop, which may not match up at all with the method you're calling. That's why you're getting invalid output, it's using an inappropriate self.p key.
I don't have a firm understanding of what you're intending to do in your methods, so I don't really have a recommended fix. But in general, I'd suggest you think more carefully about which values you're passing to which parts of your code as attributes and as arguments. self.p should probably not exist as an attribute. Maybe it should be an argument to the methods? Maybe you need different attributes to sort your data into separate containers, rather than repeatedly looping over it all. You may need to redesign your class to have its data make more sense the way you need to use it.

Accessing Methods of a class using function parameter in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a class like this in python:
class xyz:
def abc():
#Do Something
def add(x,y):
#Add x and y
def sub(x,y):
#Subtract y from x
def mul(x,y):
#multiply x ynd y
Note: Here "add", "sub" and "mul" are nested methods.
Is it allowed to make a class like this?
If it is allowed, then i want to access the methods "add", "sub" and "mul" by function parameters. for e.g.:
from xyz import xyz
def jkl(input):
abc.(input) # By doing this it will raise syntax error. This is just for refernece.
so, when i call jkl(add(2,3)) it should add the numbers. Similarly when i call jkl(sub(4,3)) it should subtract the numbers.
Can it be done?
It's hard to understand exactly what your goal is here.
EDIT: I'll leave this answer here since it has received an upvote, but OP clarified that they're actually asking how to overload operators.
You can do this:
class abc():
//Do Something
#staticmethod
def add(x,y):
# Add x and y
#staticmethod
def sub(x,y):
# Subtract y from x
#staticmethod
def mul(x,y):
# multiply x ynd y
abc.add(1,1)
If you want to use your class in another module, you can put that class definition in file xyz.py, and then in another file (in the same directory):
from xyz import abc
abc.add(1,1)
However, this is a very odd thing to do in the Python world. I'd advise organizing things differently, unless you have a really good reason to do things this way. A better way would be to skip the class definition altogether, and do this in abc.py:
def add(x,y):
# Add x and y
def sub(x,y):
# Subtract y from x
def mul(x,y):
# multiply x ynd y
Then import from that module:
import abc
abc.add(1,1)
etc...
Alternatively, you can do this:
from abc import add, sub, mul
add(1,1)
etc...

Python garbage collector [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Given the code sample below, what is the life cycle for bb in in example 1 and for self.bb in example 2
Example 1
import B
class A:
def __init__( self ):
bb = B( self )
Example 2
import B
class A:
def __init__( self ):
self.bb = B( self )
Edit:
B is another class and for some reason i found it was not garbage collected in the first example. I looked more carefully in my code and i found out B class created a new class C and gave a ref to one of its methods to that C class. In the end C instantiated a loop back thread to wait for events hence B class instance was still alive even though A class init was done.
Thanks all for your answers.
On both cases there will be no reference to the B instance until you instantiate A.
Once you instantiate A, in the first case it will be discarded right after __init__ runs because bb will be out of scope and there will be no reference left to that B instance, so it will be garbage-collected on the next GC cycle (exactly when is an implementation detail). On the second case, the reference to that B instance will exist as long as a reference for the A instance exists or until you manually remove it.
In first example bb is local variable for function __init__ The bb variable can access within the same __init__ function.
In 2nd example self.bb is Instance variables for every class object.
They has not any life-time. You have to inherited.
Example 1
import B
class A:
def __init__( self ):
B.__init__(self)
bb = B()
Example 2
import B
class A:
def __init__( self ):
B.__init__(self)
bb = B()
For more information about init

Categories

Resources