As far as I am concerned, first class usually means that:
Can be stored in a variable
Can be passed to or returned from a function
Can form complex data structure like list
So, as for Python where everything is an object, everything is first class citizen. Am I right? Even functions are first class citizens.
# functions
# can be treated as objects
def toUpper(text):
return text.upper()
print toUpper('abc')
Upperize = toUpper
print Upperize('abc')
What about R? Is everything in R is first class object? Or is there any exception?
Any thoughts would be helpful.
Related
I'm trying to create object iteratively by using a class method inside the class that the objects belong to. So everytime I call that class method it creates an object, and ads it to a dictionary with its proper idex (both are class variables). My problem comes when I want to call the same method of every object, but iteratively and with a random attribute each time. My code is large so here I coded a another program with exactly what I'm looking for so it's easier to understand.
class new_class:
objects = {} #this dictionary stores all objects of this class
i = 0 #used to iterate the dictionary and define every object separately
def __init__(self):
pass
def method(self, random): #<-- here goes the random elements that the method should be called with
return random #sample usage of the random value
#classmethod
def object_creator(cls):
cls.i += 1
cls.objects[cls.i] = cls() <-- this creates a new object of its own class and adds it to the dictionary with the key of the also iterated "i" variable
while True:
new_class.object_creator()
#Here I want to call for the method of evey existing object with random attributes
Calling the object this way, with the dictionary and its index doesn't work because it just calls the last created object, since the current index belongs to him.
while True:
new_class.object_creator()
new_class.objects[new_class.i].method()
I'm not sure if this is even possible because I would have to essentialy "create new code" for each created object. The only pseudo-solution I've found is to make another loop and make iterate through the length of the dictionary, and call the method of the object whose index is the loop's one, but that calls each method at a time and not all of them at the same time.
By default, your code is executed sequentially by a single thread, so the calls to the method will be done one after another. But it may be very quick to call all your objects' method because computers are fast. And from the point of view of the programming language, calling call_my_method_for_all_my_objects is no different than calling int("14").
If you really really (really) want to have code executed in parallel, you can have a look at multi-threading and multi-processing, but these are not easy topics. Don't bother with them if you don't actually want your program to execute faster or really need to have multiple code execution at the same time.
Using a dict instead of a list is not a real issue.
The problem with
while True:
new_class.object_creator()
new_class.objects[new_class.i].method()
is that at each iteration of the loop, it will create a new object (which increments i), then call the i-th object (newly created) method. It means that each object will have its method called only once, and in the creation order which is also i-ascending.
As for a solution, I recommand you to create a function or a method that will call for each of your objects. I decided to implement it as a static method of the class :
class new_class:
objects = {}
i = 0
def __init__(self):
pass
def method(self, random):
return random
#classmethod
def object_creator(cls):
cls.i += 1
cls.objects[cls.i] = cls()
#staticmethod # static
def call_each():
for i, obj in new_class.objects.items(): # iterate over the objects
print(obj.method(i)) # call each one's method, for example with its index
I used it like that :
# let's create 3 items for demonstration purposes
new_class.object_creator(); new_class.object_creator(); new_class.object_creator()
print(new_class.objects) # {1: <__main__.new_class object at 0x0000022B26285470>,
# 2: <__main__.new_class object at 0x0000022B262855C0>,
# 3: <__main__.new_class object at 0x0000022B262854A8>}
new_class.call_each() # prints 1 2 3
If you want to provide a random value for each call, add import random to your script and change the call_each method to :
#staticmethod
def call_each():
for obj in new_class.objects.values():
print(obj.method(random.random()))
so that
new_class.call_each() # prints 0.35280749626847374
# 0.22163283338299222
# 0.7368657784332368
If this does not answer your question, please please try to be extra clear in what you ask.
I defined class Average as follows and it gives me the average of numbers.
class Average:
#lisst=[]
def __init__(self, value):
self.value=value
#Average.lisst.append(self)
def add(self, other,k):
return Average(self.value +(other.value-self.value)/float(k))
This is the question without any changes:
First: Write a Python class calculating the mean value of numbers being passed one by one to the class. It should have a put(x) method that feeds it a number and a get() method returning the mean value of the numbers passed so far.
Second: Write a framework class that has an append(o) method that takes an object like the ones above (i.e. ones that have a put method to process data and a get method to retrieve a result). It should itself have a put(x) method, which will pass the x on to all the objects o passed to it via append and a get method which will return a list containing the results of the get calls of all the contained
objects.
I don't actually understand what is want. I just need a hint to continue. Thanks.
PS This is not a mandatory class assignment and I do not get any point for it. Just to clarify that I am NOT cheating.
First and foremost, you should direct this question to the Powers That Be of your course: the instructor, teaching assistant, etc.
Second, do you have the original assignment wording? What you've written is inconsistent or incomplete in several respects.
However, to get you going in the meantime ...
an object like the ones above (i.e. ones that have a put method to
process data and a get method to retrieve a result)
Your Average class has neither at the moment; you have to add them. It appears that add might be the processing method.
It should itself have a put(x) method, which will pass the x on to all
the objects o passed to it via append
I'm confused here. append can construct a list, but it does not pass on objects. Were I designing the system, I'd take this as a hint that my user program should collect the Average objects in a list, and pass that list to the framework's put method.
a get method which will return a list containing the results of the
get calls of all the contained objects.
The framework needs to maintain a list of objects for which it is responsible. framework.get simply iterates through the Average.get for each object, returning a list of results.
In code terms, I'm seeing something like this:
class Average:
# stuff to add
def put(self, new_value):
...
def get(self):
return self.value
class Avg_FW:
def __init__(self, avg_list):
# maintain the list of all Average objects
def put(self, new_value):
# Invoke Average.put on each average in your list
def get(self):
# Invoke Average.get on each average in your list
# Return a list of the results
Does that clarify the structure enough to continue?
Does it match what you know about the course?
Create a class with a list variable (which you have already done).
You can use the default constructor.
The add/append/put function appends the input number to the list. You could also check to verify that the input is a number (int or float/double).
The average function returns the average of the numbers in the list.
The actual implementation is left to the reader as an exercise.
I have been trying to fully understand this for a while now, and practically speaking I think I understand what happens but I can't seem to find anywhere that confirms wether I understood it correctly:
class test(object):
def __init__(self, this):
self.something = this
example = test("writing")
My question is: In the above example, is it correct that self is simply a stand-in for the instance I am creating? Meaning that when i create an instance and assign it to "example", then "example is put in place of self and behind the scenes does something resembling this:
class test(object):
def __init__(example, this):
example.something = this
example = test("writing")
Furthermore, does that also mean that as long as I am still working with this on a class basis (say in tandem with another class) I should still be using self.something, while I should be using example.something if I am working with it on an instance level?
I hope that made somewhat sense, im still trying to wrap my head properly around all of it, so let me know if I need to try and rephrase it.
For reference sake, should someone else end up asking the same, this reply: Python __init__ and self what do they do? almost did the trick for me, and only really left me a bit in doubt about the above questions.
This is correct. self is the instance of the class (i.e. the object) and you use it inside the class code (inside it's methods).
While the first argument can be named something else (example in your second code), the convention is that we always use self or the code might be highly confusing for other programmers. But you got the gist right by doing that, the example variable in the class (i.e. the self in your first code) and the example variable outside of the class is basically the same thing.
By the way, I'd also avoid the following two things:
having a class name that starts with a small leter case,
using a variable name this (since a variable named this does in some other languages essentially what self does in Python).
In Python, variables do not "contain" objects, they refer to them. So:
class test(object):
def __init__(self, this):
self.something = this
example = test("writing")
In this case example is a reference to the new object, but so is self. It is perfectly legal, and common, to have multiple references to the same object.
If you did:
another = example
this would not create a new object but have another reference to the same object. another, example (and self) would be references to the same single object.
You can test this by looking at the object's unique identifier, using id(). Add:
another = example
print id(another)
print id(example)
you will find that their id's are the same.
This is probably very much a beginner question, but I have a question about attributes.
I have a module responsible for Google Docs API actions which contains functions for retrieving information. I would like to be able to refer to certain variables from these functions as attributes.
Here is an example:
Gdocs.py
def getRows():
rows = #action for getting rows
rowsText = #action for converting to text
General.py
import Gdocs
text = Gdocs.getRows.rowstext
I know the basic effect of passing variables can be achieved by just returning the values, but I would like to refer to them as attributes if possible. Simply put, my question is, how can you create an attribute of a function that I can reference in another .py document?
Thanks and sorry if it has been already answered, I did try to search but kept running nto very specific problems.
It sounds as if you want to return a result consisting of multiple parts. Don't use function attributes for this, return a new object that can be addressed via attributes instead. That'd make it thread-safe as well, as function attributes live in the same scope as the function object itself: as a global.
The standard library has a helpful class factory function for just such return values, collections.namedtuple():
from collections import namedtuple
Point = namedtuple('Point', 'x y')
def calculate_coordinates(foo, bar, baz):
return Point(42, 81)
The return value is a tuple subclass, so it can be addressed like a tuple (with indexing), it can be unpacked into separate values, or you can use attributes:
result = calculate_coordinates(spam, ham, eggs)
print result.x, result.y
or
res_x, res_y = calculate_coordinates(spam, ham, eggs)
all work.
While I understand what you said about not wanting a class for each function...
When you have a class, you can apply the #property decorator to functions.
This has the effect of allowing you to effectively create functions that exhibit behaviors but can be called just like attributes. In the following, if you wanted to produce a list of squares based on the input list, you could create a function with a verb-like name called create_list_of_squares(). But in this case, if you really want to keep the API simple and abstract away the mechanics behind the method and simply enable users to access the attributes 'squares', you can use a property decorator, like this...
class SquareList(list):
#property
def squares(self):
return [x ** 2 for x in self]
s = SquareList([1, 2, 3, 4])
print s.squares
which will yield:
[1, 4, 9, 16]
It's a little weird, but you can use staticmethod and classes to get what you want. To wit:
source: zattr2.py
class getRows(object):
#staticmethod
def rows(arg):
return [arg, arg]
#staticmethod
def rowsText(arg):
return repr(arg)
usage:
>>> import zattr2
>>> zattr2.getRows.rowsText('beer')
"'beer'"
See: https://docs.python.org/2/library/functions.html#staticmethod
Do python class-methods have a method/member themselves, which indicates the class, they belong to?
For example ...:
# a simple global function dummy WITHOUT any class membership
def global_function():
print('global_function')
# a simple method dummy WITH a membership in a class
class Clazz:
def method():
print('Clazz.method')
global_function() # prints "global_function"
Clazz.method() # prints "Clazz.method"
# until here, everything should be clear
# define a simple replacement
def xxx():
print('xxx')
# replaces a certain function OR method with the xxx-function above
def replace_with_xxx(func, clazz = None):
if clazz:
setattr(clazz, func.__name__, xxx)
else:
func.__globals__[func.__name__] = xxx
# make all methods/functions print "xxx"
replace_with_xxx(global_function)
replace_with_xxx(Clazz.method, Clazz)
# works great:
global_function() # prints "xxx"
Clazz.method() # prints "xxx"
# OK, everything fine!
# But I would like to write something like:
replace_with_xxx(Clazz.method)
# instead of
replace_with_xxx(Clazz.method, Clazz)
# note: no second parameter Clazz!
Now my question is: How is it possible, to get all method/function calls print "xxx", WITHOUT the "clazz = None" argument in the replace_with_xxx function???
Is there something possible like:
def replace_with_xxx(func): # before it was: (func, clazz = None)
if func.has_class(): # something possible like this???
setattr(func.get_class(), func.__name__, xxx) # and this ???
else:
func.__globals__[func.__name__] = xxx
Thank you very much for reading. I hope, i could make it a little bit clear, what i want. Have a nice day! :)
I do not think this is possible and as a simple explanation why we should think about following: you can define a function and attach it to the class without any additional declarations and it will be stored as a field of the class. And you can assign the same function as a class method to 2 or more different classes.
So methods shouldn't contain any information about the class.
Clazz.method will have an attribute im_class, which will tell you what the class is.
However, if you find yourself wanting to do this, it probably means you are doing something the hard way. I don't know what you are trying to accomplish but this is a really bad way to do just about anything unless you have no other option.
For methods wrapped in #classmethod, the method will be bound and contain the reference im_self pointing to the class.