use functions in a class - python [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 8 years ago.
Improve this question
I have a couple of functions defined in my code and I want to be able to call them in one of my class.
I want to pass one of their name as an argument so I can select the right function to call in my class.
I looked for such things on internet but what I found is how to call a function defined in a class inside the same or another class. I can't define my functions inside my class because they also call other functions
So there's not too much but there's my code :
class _fonction_use_:
def __init__(self,pos,function):
self.pos=pos
self.function=function
Where "function" would be the name of one of my functions defined outside the class.
So, if fonction_use belong to this class, I want something like fonction_use.function to return the function I would assigned it before.

Since functions are first class objects, you can pass them directly to your class.
def somefunc():
pass # do something
class MyClass(object):
def __init__(self, pos, function):
self.pos = pos
self.function = function
myclass = MyClass(0, somefunc)

Related

Is it a good practice to implement a singleton-like class using class attributes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a class that contains some variables/states.
I would like to share those states with many other classes in my code.
I looked online and I saw that modules and singleton classes are a good way to this. I ended up creating a class and storing all the data as class attributes and accessing it via the class it self, like the example:
# foo.py
class Foo(object):
varx=45
def foo(x):
Foo.varx = x
And I would import the data as:
# bar.py
from foo import Foo
print(Foo.varx) #45
Foo.foo(5)
print(Foo.varx) #5
I would like to know if using classes attributes like this is an anti-pattern, or if there is a downside I am not seeing in this implementation.
Since your foo method is altering the state of the class Foo (rather than the state of any one instance of Foo), it would be more pythonic to use a classmethod in this case. Also, note that there is no need to explicitly inherit from object, as all python classes implicitly inherit from object.
class Foo:
varx = 45
#classmethod
def foo(cls, x):
cls.varx = x
Your current implementation of the foo method has the name of the class hardcoded into the implementation, which means that the implementation would break if you changed the name of the class. The implementation would also break if you had another class inheriting from Foo which you wanted to be able to implement the methods of Foo, as the class inheriting from Foo would have a different name.

Can you access attributes that were created with the init method from other methods in the class? [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
When I write the __init__ method and assign attributes, can I access those attributes in other methods (functions) that I write in that class? If so, how is it done?
I've googled this but couldn't find an answer. I Haven't been able to wrap my head around this one.
Use self:
class MyClass:
def __init__(self):
self.name = 'John'
def other_method(self):
print(self.name)
other_method will print "John".
When you make a class and set an instance (like first_class = MyClass()) the def __init__(self): is run or initialised. Any variables in there, like self.name are able to be accessed from within the class and its functions, as well as when you use a class in another program. self kinda attaches that variable to that class.
Basically using Allure's example:
class MyClass:
def __init__(self):
self.name = "John"
def show_name(self):
print(self.name)
Then use MyClass's name outside of class, in a program:
firstClass = MyClass()#Initialise MyClass and its variables
print(firstClass.name)
Or:
firstClass= MyClass()
firstClass.show_name()
Both output:
'John'
(still putting up this answer for others, hope you don't mind :) )

can a self variable be defined inside the for loop? [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 4 years ago.
Improve this question
can a self variable be defined inside the for loop? it is not defined anywhere before.
I am confused over its usage. the link from where the code is attached below.
def initialize_nb_dict(self):
self.nb_dict = {}
for label in self.labels:
self.nb_dict[label] = defaultdict(list)
https://github.com/taspinar/siml/blob/master/notebooks/Naive_Bayes.ipynb
Yes, it can. self is the class instance; you can create and set attributes. In the same way that you can do:
>>> class A: pass
...
>>> a = A()
>>> a.nb_dict = {}
>>> a.nb_dict[1] = 2
>>> a.nb_dict
{1: 2}
Within the scope of the method initialize_nb_dict(), self is the instance (like a above.)
There's nothing special about self, except that it is used by convention to refer to the instance for instance methods. (You could even call a as self, but it would be unconventional to name an instance self outside of an instance method.)
One other minor point on terminology: you say "can a self variable be defined." It's probably more accurate to say that an attribute of self is being set, rather than that self is being defined; it's "defined" when the instance is implicitly passed as self to the method.

How to make objects accessible from anywhere within it's 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 8 years ago.
Improve this question
As a general strategy, is there a way to add objects to init, without initialization, while the code is being executed. For example, instead of:
class Test:
def __init__(self):
self.a = False
self.b = False
def set_values(self, in_boolean):
if in_boolean:
self.a = True
else:
self.b = True
Do this:
class Test:
def __init__(self):
self.a = False
def set_values(self, in_boolean):
if in_boolean:
self.a = True
else:
self.b = True
# This object is only created if this condition is
# met. Otherwise, this is not created in __init__.
Does one need to initialize any and all objects in __init__ if they want to save an object there?
If this is not possible, what is an alternative method for creating global objects that are created within a class method?
I'll explain a scenario when I would want to use this so as to better illustrate the question:
Say I am executing a method within a class. Depending on certain conditions, an object may or may not be generated within that class that I would like to be able to access from all other methods within the class. Because the object may or may not be created, I don't wish to initialize it in __init__.
To sum it up: If I want to 'save' an object on my class, do I need to initialize it in __init__?
EDIT
Ok so my problem was that I believed one only created "self." objects in init. As I understand it now, one can make a "self." object anywhere in the class, not just in init. This would make said object accessible from anywhere else in the class, which is ultimately what I am looking for here. Maybe the question should have been:
How to I make objects accessible from anywhere in it's class?
In Python, you don't need to 'declare' a variable before you use it at all. If you try to access a variable that doesn't exist, you can just wrap it in a try...except AttributeError and call it a day.
The __init__ on a class is just like any other method on Python, it doesn't have access to any sort of functionality that the others don't. The only difference is that it has the benefit of being automatically called whenever you instantiate your class, saving you the trouble of having to write a constructor-like class every time and call it manually.

Python: how to maintain independence from instance? [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 8 years ago.
Improve this question
I'm refactoring a program of mine. Basically I move all classes into a module.
Now I'm facing the problem that some of the module code is dependent on instances of a class I instantiated in my main program. Of course I could pass the instance to the method directly. Or pickle the instance. Or define the attribute as global. Which is the best way to go?
One possibility might be to pass the instance to the class upon instantiation:
class Bar(object):
def __init__(self, inst):
self.inst = inst
def method(self):
# use self.inst
inst = Foo()
bar = Bar(inst)

Categories