How to use a character as attribute of a function
(Update: Make sure to see Hadley's answer for the better way of doing this, without resorting to string-pasting. My answer will still be useful for explaining why that is harder-than-usual in this case.)
The peculiarities of mcp()
require you to use the relatively brute force approach of pasting together the expression you'd like to evaluate and then passing it through eval(parse())
.
The tricky bit is that mcp()
interprets its first argument in a nonstandard way. Within mcp()
, x1 = 'Tukey'
does not (as it normally would) mean "assign a value of 'Tukey'
to the argument x1
". Instead, the whole thing is interpreted as a symbolic description of the intended contrasts. (In this, it is much like more familiar formula objects such as the y ~ x1 + x2
in your lm()
call).
for(var in c('x1', 'x2')) {
# Construct a character string with the expression you'd type at the command
# line. For example : "mcp(x1 = 'Tukey')"
exprString <- paste("mcp(", var, "='Tukey')")
# eval(parse()) it to get an 'mcp' object.
LINFCT <- eval(parse(text = exprString))
mc1 <- glht(fm1, linfct = LINFCT)
print(summary(mc1))
}
How do I properly use a function under a class?
If you want to use it like a property in C#, decorate the function with @property
, like so:
class Character:
def __init__(self,Id,Hp,Mana):
self.Id=Id;
self.Hp=Hp;
self.Mana=Mana;
@property
def Score(self):
return (self.Hp+self.Mana)*10;
MyChar=Character(10,100,100);
print(MyChar.Score)
So you don't have to call it like a function.
For more advanced usage of properties (e.g. also having a setter func), see the official docs: https://docs.python.org/3/library/functions.html#property
Accessing char attribute of a struct
Function getEntry
returns the address of a non-static local variable. Using this address in main
is undefined behavior. Probably the call to printEntry
partially overwrites the data, that's why you see different output.
You try to dynamically allocate memory for the returned data with
Entry *pntEntry = malloc(sizeof(struct Entry));
but you throw away the address to this memory and assign the address of your local variable with
pntEntry = &entry;
You probably want to copy the structure instead of the pointer. This would be
*pntEntry = entry;
Not related to your problem:
Your program should free
all allocated memory when it is no longer used.
With the code shown in the question it is not necessary to pass the address of the pointer to the input string to getEntry
and separateBySpace
as a type char**
because you don't want to modify the pointer. Passing a char*
would be sufficient.
In separateBySpace
you return an array of pointers that point to characters of the input string which gets modified by strtok
. Later in getEntry
you assign the pointer password
to a pointer in your Entry
structure. This means you should not change the string variable that was passed as an argument to getEntry
, otherwise the password´ string referenced in the returned
Entry` structure will change.
Edit (to answer a comment):
I think in getEntry
you can free
the pointer array allocated in separateBySpace
because all values have been used or copied to the Entry
structure.
At the end of the program you should free
the memory pointed to by entry
that was allocated in getEntry
.
You must not free
the memory password
because this points to a character in your local variable line
. Freeing entry->password
before freeing entry
would be necessary if you would allocate memory for a copy of the password, for example using strdup
. This would also fix the possible problem that entry->password
points to an element of line
.
Python how to pass class function from instance to another class
Please post the traceback error messages. I think the problem is in Milestone1()
you check self.power
and self.position
but self refers to the instance of Character
not Player
, and character has no power or position attributes.
Here are 2 fixes I can think of:
Inheritance: If you make player a subclass of character, then player would have all of the attributes of character and therefore be able to call
ms1()
class Player(Character):
def __init__(self, player_num, name):
# self.character = Character(name) <-- not needed
# self.ms1 = self.character.Milestone1 <-- not needed
# since Player is a subclass of Character,
# use super to init & it already has name and Milestone1
super().__init__(name) # Py3 usage
# super(Player, self).__init__(name) # Py2 usageI tested this out in a simple example on repl.it
and it works for me, try it by pressing play, output is'n'
, then't'
.Note: in Python-2, the syntax for
super
is different than Python-3, and you must also supply the subclass,Player
, and the instance,self
as args. I tested inheritance withsuper(Player, self).__init__(name)
in this sample repl.it using Python-2 and it also works.Also Note: Python-2 classes should subclass
object
to create new-style classes.Composition:Fix
Milestone1()
so it uses player as an argument, and therefore has access to power and positionclass Character:
# no change
def Milestone1(self, player):
if self.name == 'char x':
if player.power >= 20:
return True
else:
return Falseupdate
Player
too, passing the player instance toMilestone1
class Player:
def __init__(self, player_num, name):
self.character = Character(name)
# self is the Player, lambda makes ms1 callable
self.ms1 = lambda: self.character.Milestone1(self)Although then the
name
attribute isn't really used, and this seems a bit hacky, but I tested it in this simple repl.it example and it also works.
In general, I think this is a good opportunity to use inheritance over composition. Ask yourself:
Is a player a character? (Inheritance: #1)
Does a player have a character? (Composition: #2)
How to set a specific attribute of an object if the object name is in a variable?
You can use a function to apply the attributes and the assign function to apply them:
add_dummy <- function(obj, name, attribute){
attr(obj, name) <- attribute
return(obj)
}
assign(var, add_dummy(get(var), "attr_name", list(dummy = 123)))
What is getattr() exactly and how do I use it?
getattr(object, 'x')
is completely equivalent to object.x
.
There are only two cases where getattr
can be useful.
- you can't write
object.x
, because you don't know in advance which attribute you want (it comes from a string). Very useful for meta-programming. - you want to provide a default value.
object.y
will raise anAttributeError
if there's noy
. Butgetattr(object, 'y', 5)
will return5
.
Special char in attribute
Colons aren't valid parts of identifiers in Python, but you can sidestep this by splatting a dict:
category = ET.SubElement(
messagedata,
"catid",
**{
"xmlns": "EE.Schema.VSOP.V1R00",
"xmlsn:comDef": "EE.Schema.V1R00",
}
)
As an aside, though, if that's supposed to be xmlns:comDef
, you should not be managing namespace aliases by hand, but by using the namespace mapping features and spelling out namespaced attributes; "comDef:foo"
with that namespace would be {EE.Schema.V1R00}foo
and the XML serialization engine would take care of ensuring there are suitable xmlns:...
attributes somewhere.
Related Topics
Combine Rows and Sum Their Values
Get Continent Name from Country Name in R
Update() Inside a Function Only Searches the Global Environment
Custom Ggplot2 Axis and Label Formatting
How to Insert Appendix After References in Rmd Using Rstudio
Math of Tm::Findassocs How Does This Function Work
Why Is Date Is Being Returned as Type 'Double'
Add Hline with Population Median for Each Facet
Why Does ".." Work to Pass Column Names in a Character Vector Variable
Visualising and Rotating a Matrix
Wrapping Base R Reshape for Ease-Of-Use
No Dimensions of Non-Empty Numeric Vector in R
Can You More Clearly Explain Lazy Evaluation in R Function Operators
Calculating Standard Deviation Across Rows
Converting Between Matrix Subscripts and Linear Indices (Like Ind2Sub/Sub2Ind in Matlab)