i want to make a vb program that asks random questions in a label with predefined multiple choices from option buttons. Each question and multiple choices should be in a specific sub procedure. so that if there are 10 questions to be asked, then there will be 10 sub procedures for the questions. Since i want the questions to be asked at random without a specific order, i want to put the question sub procedures in an array in that i can use the randomize function to call the procedures randomly.
i.e putting these two sub procedures into an array
private sub question1()
lblquestion.caption = "What is 1 + 1"
opt1.caption="A. 2"
opt2.caption="B. 3"
end sub
private sub question2()
lblquestion.caption = "What is 5 + 1"
opt1.caption="A. 4"
opt2.caption="B. 6"
end sub
(Much of the meat of this answer is copied from my other answer on calling a function by its name as a String, and while this question may be a duplicate some people may find it helpful to describe the solution in this context as well.)
VB6 is in many ways an object-oriented language. Even if it may not have quite as much object-orientedness as C# or Java might in some respects, it does support multiple classes and polymorphism. As such, if you're trying to do something where you want to select one of several implementations at runtime, you clearly just want to have multiple classes, and select which object at runtime to use.
In fact, VB6 even lets you define real actual Interfaces. (They just happen to look like any other class module, but without any content in the functions.) Create a Class Module to use for your interface, say named MyInterface:
Public Sub DoStuff()
End Sub
Then, create your ten Class Modules, one for each possible implementation of the Interface:
In MyClassOne:
Implements MyInterface
Public Sub MyInterface_DoStuff()
Msgbox "I'm function one"
End Sub
Then, in MyClassTwo, the same thing but with another implementation:
Implements MyInterface
Public Sub MyInterface_DoStuff()
Msgbox "I'm function two"
End Sub
And so forth. The array you want to create isn't really of the methods, but of the objects that implement your defined interface:
Dim MyObjects(10) As MyInterface
Set MyObjects(1) = New MyClassOne
Set MyObjects(2) = New MyClassTwo
' and so on
Now, you can figure out which implementation you want, and just call it:
Dim WhichObject As Integer
WhichObject = SomehowSelectANumber()
MyObjects(WhichObject).DoStuff
For further reading in the MSDN library:
How Visual Basic Provides Polymorphism
Creating and Implementing an Interface
Creating Interfaces for Use With the Implements Statement
Implements Statement reference
i manage to somwhow find a simpler way through #bob77 idea of using decision making statements. i chose to use select case as a possible solution and of course its simplicity. i however got rid of the array(guess this will no longer be answering the question as it is, but will still implement what was expected). here is the code.
dim q as integer
private sub cmdask_click()
Randomize
q = int((rnd * 10)+1)
select case q
case 1
call question1
case 2
call question2
'and so on..
End select
however, the biggest limitation about this is that the code will really be bulky(assume the program was to have 100 questions) and also repetition of questions will be an issue (i am learner i don,t know how to deal with that) I will really appreciate if anyone will suggest a code that will deal with repetition and bulkiness.(Yes I know there might be already answered questions on repetition and bulkiness. i just want a more customized code to this thread.)
Related
Tldr: how do I 'include Shoes methods' into the Array class and classes ive created, with minimal code, without totally restructuring everything?
I've written a functioning program in Ruby, and now I want to make a Shoes app from it.
I'm having the problem described at the beginning of the manual - Shoes.app is a sort of block in itself, so self always refers to it, and Shoes methods like "para" aren't necessarily going to be available everywhere the way "puts" is in Ruby. But I'm not smart enough to fix it (I've only just got my head around using self and return in pure Ruby, bear with me)
For example, I've created a new method for Array: putdata, which loops through a student's test score array displaying each automatically as a list:
self.each do |ea|
puts/para "#{ea.topic}: #{ea.score}"
end
Works in ruby. Doesn't work in Shoes: Array class doesn't have access to the method para. I've tried:
making Array < Shoes (it really doesn't like that)
adding stack.app do...end at various places in the program (no impact)
trying to call Shoes::para instead of para (farts)
I've tried using require 'file with all my classes and methods in.rb' instead of the same code in the file (reports no method for class)
tried requiring my code directly before calling a method, to ensure my code is in the scope of Shoes (reports no method for class)
making my custom classes (Course and Student) < Shoes, so it'd have access to its methods (causes a runtime error)
I've got it to function by:
1. Removing this bit of code from the Array class, and making it a floating/generic method rather than an Array method
2. Private method error --> then rephrasing it so instead of an Array method (array.putdata) it's a generic method which takes an array as an argument (putdata(array))
But I really, really don't want to go through my code and individually un-organise it like this.
It's my first 1000 line program, with 42 methods, and I worked hard on making it as maintainable and neat as possible, with everything tucked away in classes or methods for easy upkeep. I got it from everything in massive, step-by-step generic methods down to lots of snappy ones, which seemed a bit more like how OOP is meant to go. Now the only way I can see to make this work is to UN-OOP it, and have no class methods or anything.
I was hoping I could Shoes the program fairly seamlessly from this tidy, functional back-end: the Ruby program has lots of "if string == "SAVE", save(student); else...", so I was hoping to straightforwardly pop in "button.click {save(student)}" with the same back code.
#
Is there something fundamental I'm missing to let me do this? And can I fix the para problem easily, seeing as all my classes contain ways of displaying their own data? I'd like to copypasta "include 'Shoes methods'" at the top of each class and be done.
Or do I need to be writing with the GUI in mind from the start in future?
(Info about my program:
Layout is a series of pages, linked from a sidebar, using index with linked pages as copied straight from the Nobody Knows Shoes book, or the class-book sample.
Students can input their new levels, and view a readout of their current progress.
There are generic methods for major "parts" of the program, which have things like the title of the page and some instructions, and which then call on student objects or Module methods to do the things as instructed by the user.
Higher up: student is a custom class, with methods like "save", "display flattened data ", "add one to your level IF this ELSE don't", and associated bits of data, like an array with all their course objects in.
Each course is also a custom class ("Module"), which has the score, the module name etc as variables, and some tiny methods like display formatted name, or add one to this module.)
I'm glad to see a question about shoes, it's been a long time.
You'r new on SO so first: your question is way too elaborated, too much to read and far too little information to help you.
You need to provide piecess of code that give error or don't do what you expect, things we can take over and try. This means extracting from your code tests or pieces of code that run by themself and show the problem.
We also need to know which Ruby version and which version and color of shoes you are using. The example I'll be using is green shoes.
I'm sure the following isn't exactly what you were after but I've made a sample based on your description of an Array that needs to be listed both by puts and para.
Change the question or make a new one if this is not what you are after.
require 'green_shoes'
s = Struct.new(:topic, :score)
s1 = s.new("test1", 1)
s2 = s.new("test2", 2)
A = [s1, s2]
class Array
def putsdata(shoes = nil)
if shoes.class == Shoes::App
self.each do |ea|
shoes.para "#{ea.topic}: #{ea.score}"
end
else
self.each do |ea|
puts "#{ea.topic}: #{ea.score}"
end
end
end
end
A.putsdata
# gives in the console
# test1: 1
# test2: 2
Shoes.app do
A.putsdata(self)
end
# gives in a graphic window
# test1: 1
# test2: 2
The puts also works in the shoes block, but of course the result doesn't come in the graphic window but on the console where you started, after the first list.
I'm not really sure how to phase it any other way.
The thing is, i'm trying to merge functions with the same name in vbs. Sometimes, the function appears in different forms in other parts of the system. If they are too different, I regretfully leave them as they are. However, if the differences are minor (like having one of the functions only having one variable more than the others, which i can then check for in-function), I'd like to add a variable that would be a stand in.
I already know that Optional variables are not possible in vbs, and I've already had experience with passing an array of variants (works like a charm), but I believe this case is a bit different.
Dim is not correct here. You can do for example:
Public Function MagicFunction(intData1, ByRef intData2, ByVal intData3)
' some code
End Function
and to call it:
MagicFunction 3, iCount, ""
to have "optional arguments", you can only use an array an parse it (for example using UBound(aTab) to select the correct case
Public Function MagicFunction(ByVal aTab)
Select Case UBound(aTab)
Case 1: MagicFunction1 aTab(1)
Case 2: MagicFunction2 aTab(1), aTab(2)
Case Else: MsgBox "function called with more than 2 args" '<-- Should never go there
End Select
End Function
With different version of your function depending on the number of argument, MagicFunction1, MagicFunction2... It's ugly but do the trick!
Another possibility is to use empty strings as argument, and define how your function ignore a part when the string is empty (or to be more accurate, call with a specific key, like "IGNORE_KEY")
I hope I'm answering your question!
I have one project which provides a service to the others, and the return value of the method that provides this service is String. Within that project, I use some named constants to represent special out of band values that are returned in lieu of expected or recoverable errors, otherwise the service returns an XML string.
Something like the following:
' modService.bas
const SERVICE_BADARG as String = "Unsupported argument."
const SERVICE_TOOMANY as String = "Too many Foos."
' cServiceProvider.cls
Private Function GetXMLString() as String
' generate and return XML string holding all sorts of generic stuff
End Function
Public Function PerformService(argument as String) as String
' do some stuff
If (some_condition = true) Then
PerformService = SERVICE_BADARG
Else If (some_other_condition = true) Then
PerformService = SERVICE_TOOMANY
Else
PerformService = GetXMLString()
I'd like to be able, from other projects, be able to get at these constants without redundantly defining them. If possible, I'd also like to avoid putting them in the class (where they will be duplicated unnecessarily) and to avoid making a property for each one.
They are all constants, none of them ever change.
Why not just define the constants in a CONSTANTS.BAS module, and then include that in each project? That way, to VB it would look like the definitions were duplicated, but from your perspective as a developer and a maintenance programmer, the definitions would all be collected in a single place?
Another option would be to create a DLL that defined the constants, but that would make using the values of those constants more costly in all of your code because rather than being compiled directly into the object code, they would have to be retrieved from a call to an external DLL. That seems like overkill for something that is truly constant.
Consider that a "constant" value is not necessarily the same thing as a "read-only" value. A constant value, like pi, will never change, so there is really not much to be lost by duplicating those values. You won't ever need to go back in and change them. Read-only values (like your error message strings) might change, so they're not really constants. It might make sense to place those into a DLL. Especially since performance isn't all that critical when all you're trying to do is shown an error message.
Unfortunately, VB gives you no mechanism of embedding constants into DLLs for compile-time use. You would have to return properties, as you said you didn't want to do.
I would definitely use the BAS route, unless there is a reason against it. An alternative to this would be to create a type library, and define the string constants in there. To do this, you will have to learn ODL, and use the MkTypeLib.exe program which comes with VB6. Or, if you somehow have access to "Advanced Visual Basic 6.0" by Matt Curland, there is a tool which allows you to create type libraries.
I know this is old, but in case anyone is still wondering...
try this pattern:
Public Function SERVICE_BADARG() As String
SERVICE_BADARG = "Unsupported argument."
End Function
Public Function SERVICE_TOOMANY() As String
SERVICE_TOOMANY = "Too many Foos."
End Function
Or more compactly with colons to put stuff on the same line:
Public Function SERVICE_BADARG() As String: SERVICE_BADARG = "Unsupported argument.": End Function
Public Function SERVICE_TOOMANY() As String: SERVICE_TOOMANY = "Too many Foos.": End Function
You could see a constant as a function without arguments. The advantage is that a function can be public, so you don't have to create a DLL. It also gets around only being able to declare them before other functions. VB6 allows you to hide the brackets:
x = "error: " & SERVICE_TOOMANY
Select Case y
Case SERVICE_BADARG
z = "error: y is a bad arg"
Case SERVICE_TOOMANY
z = "error: y is too many"
End Select
The disadvantage is a little overhead, but this is typically negligible
I have a public method which uses a variable (only in the scope of the public method) I pass as a parameter we will call A, this method calls a private method multiple times which also requires the parameter.
At present I am passing the parameter every time but it looks weird, is it bad practice to make this member variable of the class or would the uncertainty about whether it is initialized out way the advantages of not having to pass it?
Simplified pseudo code:
public_method(parameter a)
do something with a
private_method(string_a, a)
private_method(string_b, a)
private_method(string_c, a)
private_method(String, parameter a)
do something with String and a
Additional information: parameter a is a read only map with over 100 entries and in reality I will be calling private_method about 50 times
I had this same problem myself.
I implemented it differently in 3 different contexts to see hands-on what are result using 3 different strategies, see below.
Note that I am type of programmer that makes many changes to the code always trying to improve it. Thus I settle only for the code that is amenable to changes, readbale, would you call this "flexible" code. I settle only for very clear code.
After experimentation, I came to these results:
Passing a as parameter is perfectly OK if you have one or two - short number - of such values. Passing in parmeters has very good visibility, clarity, clear passing lines, well visible lifetime (initialization points, destruction points), amenable to changes, easy to track.
If number of such values begin to grow to >= 5-6 values, I swithc to approach #3 below.
Passing values through class members -- did not do good to clarity of my code, eventually I got rid of it. It makes for less clear code. Code becomes muddled. I did not like it. It had no advantages.
As alternative to (1) and (2), I adopted Inner class approach, in cases when amount of such values is > 5 (which makes for too long argument list).
I pack those values into small Inner class and pass such object by reference as argument to all internal members.
Public function of a class usually creates an object of Inner class (I call is Impl or Ctx or Args) and passes it down to private functions.
This combines clarity of arg passing with brevity. It's perfect.
Good luck
Edit
Consider preparing array of strings and using a loop rather than writing 50 almost-identical calls. Something like char *strings[] = {...} (C/C++).
This really depends on your use case. Does 'a' represent a state that your application/object care about? Then you might want to make it a member of your object. Evaluate the big picture, think about maintenance, extensibility when designing structures.
If your parameter a is a of a class of your own, you might consider making the private_method a public method for the variable a.
Otherwise, I do not think this looks weird. If you only need a in just 1 function, making it a private variable of your class would be silly (at least to me). However, if you'd need it like 20 times I would do so :P Or even better, just make 'a' an object of your own that has that certain function you need.
A method should ideally not pass more than 7 parameters. Using the number of parameters more than 6-7 usually indicates a problem with the design (do the 7 parameters represent an object of a nested class?).
As for your question, if you want to make the parameter private only for the sake of passing between private methods without the parameter having anything to do with the current state of the object (or some information about the object), then it is not recommended that you do so.
From a performance point of view (memory consumption), reference parameters can be passed around as method parameters without any significant impact on the memory consumption as they are passed by reference rather than by value (i.e. a copy of the data is not created). For small number of parameters that can be grouped together you can use a struct. For example, if the parameters represent x and y coordinates of a point, then pass them in a single Point structure.
Bottomline
Ask yourself this question, does the parameter that you are making as a members represent any information (data) about the object? (data can be state or unique identification information). If the answer to his question is a clear no, then do not include the parameter as a member of the class.
More information
Limit number of parameters per method?
Parameter passing in C#
I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.
I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway).
The following solution seems to work.
# This class comes from an external library. I don't (want) to control
# it, and I want to be open to changes that get made to the class
# by the library provider.
class Programmer(object):
def __init__(self,name):
self._name = name
def greet(self):
print "Hi, my name is %s." % self._name
def hard_work(self):
print "The garbage collector will take care of everything."
# This is my subclass.
class C_Programmer(Programmer):
def __init__(self, *args, **kwargs):
super(C_Programmer,self).__init__(*args, **kwargs)
self.learn_C()
def learn_C(self):
self._knowledge = ["malloc","free","pointer arithmetic","curly braces"]
def hard_work(self):
print "I'll have to remember " + " and ".join(self._knowledge) + "."
# The questionable thing: Reclassing a programmer.
#classmethod
def teach_C(cls, programmer):
programmer.__class__ = cls # <-- do I really want to do this?
programmer.learn_C()
joel = C_Programmer("Joel")
joel.greet()
joel.hard_work()
#>Hi, my name is Joel.
#>I'll have to remember malloc and free and pointer arithmetic and curly braces.
jeff = Programmer("Jeff")
# We (or someone else) makes changes to the instance. The reclassing shouldn't
# overwrite these.
jeff._name = "Jeff A"
jeff.greet()
jeff.hard_work()
#>Hi, my name is Jeff A.
#>The garbage collector will take care of everything.
# Let magic happen.
C_Programmer.teach_C(jeff)
jeff.greet()
jeff.hard_work()
#>Hi, my name is Jeff A.
#>I'll have to remember malloc and free and pointer arithmetic and curly braces.
However, I'm not convinced that this solution doesn't contain any caveats I haven't thought of (sorry for the triple negation), especially because reassigning the magical __class__ just doesn't feel right. Even if this works, I can't help the feeling there should be a more pythonic way of doing this.
Is there?
Edit: Thanks everyone for your answers. Here is what I get from them:
Although the idea of reclassing an instance by assigning to __class__ is not a widely used idiom, most answers (4 out of 6 at the time of writing) consider it a valid approach. One anwswer (by ojrac) says that it's "pretty weird at first glance," with which I agree (it was the reason for asking the question). Only one answer (by Jason Baker; with two positive comments & votes) actively discouraged me from doing this, however doing so based on the example use case moreso than on the technique in general.
None of the answers, whether positive or not, finds an actual technical problem in this method. A small exception is jls who mentions to beware of old-style classes, which is likely true, and C extensions. I suppose that new-style-class-aware C extensions should be as fine with this method as Python itself (presuming the latter is true), although if you disagree, keep the answers coming.
As to the question of how pythonic this is, there were a few positive answers, but no real reasons given. Looking at the Zen (import this), I guess the most important rule in this case is "Explicit is better than implicit." I'm not sure, though, whether that rule speaks for or against reclassing this way.
Using {has,get,set}attr seems more explicit, as we are explicitly making our changes to the object instead of using magic.
Using __class__ = newclass seems more explicit because we explicitly say "This is now an object of class 'newclass,' expect a different behaviour" instead of silently changing attributes but leaving users of the object believing they are dealing with a regular object of the old class.
Summing up: From a technical standpoint, the method seems okay; the pythonicity question remains unanswered with a bias towards "yes."
I have accepted Martin Geisler's answer, because the Mercurial plugin example is a quite strong one (and also because it answered a question I even hadn't asked myself yet). However, if there are any arguments on the pythonicity question, I'd still like to hear them. Thanks all so far.
P.S. The actual use case is a UI data control object that needs to grow additional functionality at runtime. However, the question is meant to be very general.
Reclassing instances like this is done in Mercurial (a distributed revision control system) when extensions (plugins) want to change the object that represent the local repository. The object is called repo and is initially a localrepo instance. It is passed to each extension in turn and, when needed, extensions will define a new class which is a subclass of repo.__class__ and change the class of repo to this new subclass!
It looks like this in code:
def reposetup(ui, repo):
# ...
class bookmark_repo(repo.__class__):
def rollback(self):
if os.path.exists(self.join('undo.bookmarks')):
util.rename(self.join('undo.bookmarks'), self.join('bookmarks'))
return super(bookmark_repo, self).rollback()
# ...
repo.__class__ = bookmark_repo
The extension (I took the code from the bookmarks extension) defines a module level function called reposetup. Mercurial will call this when initializing the extension and pass a ui (user interface) and repo (repository) argument.
The function then defines a subclass of whatever class repo happens to be. It would not suffice to simply subclass localrepo since extensions need to be able to extend each other. So if the first extension changes repo.__class__ to foo_repo, the next extension should change repo.__class__ to a subclass of foo_repo and not just a subclass of localrepo. Finally the function changes the instanceø's class, just like you did in your code.
I hope this code can show a legitimate use of this language feature. I think it's the only place where I've seen it used in the wild.
I'm not sure that the use of inheritance is best in this case (at least with regards to "reclassing"). It seems like you're on the right track, but it sounds like composition or aggregation would be best for this. Here's an example of what I'm thinking of (in untested, pseudo-esque code):
from copy import copy
# As long as none of these attributes are defined in the base class,
# this should be safe
class SkilledProgrammer(Programmer):
def __init__(self, *skillsets):
super(SkilledProgrammer, self).__init__()
self.skillsets = set(skillsets)
def teach(programmer, other_programmer):
"""If other_programmer has skillsets, append this programmer's
skillsets. Otherwise, create a new skillset that is a copy
of this programmer's"""
if hasattr(other_programmer, skillsets) and other_programmer.skillsets:
other_programmer.skillsets.union(programmer.skillsets)
else:
other_programmer.skillsets = copy(programmer.skillsets)
def has_skill(programmer, skill):
for skillset in programmer.skillsets:
if skill in skillset.skills
return True
return False
def has_skillset(programmer, skillset):
return skillset in programmer.skillsets
class SkillSet(object):
def __init__(self, *skills):
self.skills = set(skills)
C = SkillSet("malloc","free","pointer arithmetic","curly braces")
SQL = SkillSet("SELECT", "INSERT", "DELETE", "UPDATE")
Bob = SkilledProgrammer(C)
Jill = Programmer()
teach(Bob, Jill) #teaches Jill C
has_skill(Jill, "malloc") #should return True
has_skillset(Jill, SQL) #should return False
You may have to read more about sets and arbitrary argument lists if you aren't familiar with them to get this example.
This is fine. I've used this idiom plenty of times. One thing to keep in mind though is that this idea doesn't play well with old-style classes and various C extensions. Normally this wouldn't be an issue, but since you are using an external library you'll just have to make sure you're not dealing with any old-style classes or C extensions.
"The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change it's class." - Head First Design Pattern. Something very similar write Gamma et.al. in their Design Patterns book. (I have it at my other place, so no quote). I think that's the whole point of this design pattern. But if I can change the class of an object at runtime, most of the time i don't need the pattern (there are cases when State Pattern does more than simulate a class change).
Also, changing class at runtime doesn't always work:
class A(object):
def __init__(self, val):
self.val = val
def get_val(self):
return self.val
class B(A):
def __init__(self, val1, val2):
A.__init__(self, val1)
self.val2 = val2
def get_val(self):
return self.val + self.val2
a = A(3)
b = B(4, 6)
print a.get_val()
print b.get_val()
a.__class__ = B
print a.get_val() # oops!
Apart from that, I consider changing class at runtime Pythonic and use it from time to time.
Heheh, fun example.
"Reclassing" is pretty weird, at first glance. What about the 'copy constructor' approach? You can do this with the Reflection-like hasattr, getattr and setattr. This code will copy everything from one object to another, unless it already exists. If you don't want to copy methods, you can exclude them; see the commented if.
class Foo(object):
def __init__(self):
self.cow = 2
self.moose = 6
class Bar(object):
def __init__(self):
self.cat = 2
self.cow = 11
def from_foo(foo):
bar = Bar()
attributes = dir(foo)
for attr in attributes:
if (hasattr(bar, attr)):
break
value = getattr(foo, attr)
# if hasattr(value, '__call__'):
# break # skip callables (i.e. functions)
setattr(bar, attr, value)
return bar
All this reflection isn't pretty, but sometimes you need an ugly reflection machine to make cool stuff happen. ;)
This technique seems reasonably Pythonic to me. Composition would also be a good choice, but assigning to __class__ is perfectly valid (see here for a recipe that uses it in a slightly different way).
In ojrac's answer, the break breaks out of the for-loop and doesn't test any more attributes. I think it makes more sense to just use the if-statement to decide what to do with each attribute one at a time, and continue through the for-loop over all attributes. Otherwise, I like ojrac's answer, as I too see assigning to __class__ as weird. (I'm a beginner with Python and as far as I remember this is my first post to StackOverFlow. Thanks for all the great information!!)
So I tried to implement that. I noticed that dir() doesn't list all the attributes. http://jedidjah.ch/code/2013/9/8/wrong_dir_function/ So I added 'class', 'doc', 'module' and 'init' to the list of things to add if they're not there already, (although they're probably all already there), and wondered whether there were more things dir misses. I also noticed that I was (potentially) assigning to 'class' after having said that was weird.
I will say this is perfectly fine, if it works for you.