can a self variable be defined inside the for loop? [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
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.

Related

Python class fuction that takes self variable as argument [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 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I want to write a function that sets a self variable to None, but it feels very wrong to write a million functions for each variable.
I want to do something like:
class MyClass():
def __init__(self):
self.duck = None
self.dog = None
def makeduck(self):
self.duck = "Duck"
def makedog(self):
self.dog = "Dog"
def deleteVar(self,var):
self.var = None # or del self.var
I want to do this because the variables tend to be very large and I don't want to overload my ram so I have to delete some not needed vars depending on the context.
It is indeed possible.
Although having a clear separation between what should be program structure: variables, and data: text inside strings, Python allows one to retrieve and operate on variables or attributes given their name.
In this case, you will want to use the setattr and delattrcalls: both take an instance, an attribute name, given as textual data (a string), and operate on them like the corresponding assignment (self.var = xxx) and deleting (del self.var ). statements (but, as you intend to use, with "var" being a variable containign the actual attribute name).
def deleteVar(self, var):
# setattr(self, var, None). #<- sets attribute to None
delattr(self, var). # <- deletes attribute.
(for completeness: there is also the getattr call which allows attribute retrieval on the same bases)
That said: the memory usage of hard-coded variables, even if you have tens of them, will likely be negligible in a Python process.
Having tens of different "deleter" methods, however, would indeed be clumsy, and there are situations were your code might be more elegant by passing your attributes as data, as you intent.

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.

make a class variable become an instance variable? [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 2 years ago.
Improve this question
I try to create a class_variable in my_class, then I change the value of class_variable by a class instance. After the change, does the class_variable is still belong to a class variable, or belong to an instance variable? Here is my code:
class my_class:
class_variable = 'belong to class'
my_instance = my_class()
print(my_instance.class_variable)
my_instance.class_variable = 'belong to instance'
print(my_instance.class_variable)
# return
>>>> belong to class
>>>> belong to instance
my_class is a class.
my_class.class_variable is a class variable.
my_instance is a global variable whose value is an instance of my_class.
class_var_class is a global variable whose value is the same as that of my_class.class_variable. It is not itself a class variable.
After you reassign my_instance.class_variable, it creates a new instance variable that shadows the class variable. (In general, you don't want to do this! Give your instance variables and class variables different names, and define all your instance variables in your class's __init__ method rather than sticking them on later.)
class_var_instance is a global variable which has the same value as the one you just assigned to my_instance.class_variable.

What the purpose of creating class instance attibutes directly in the code [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 2 years ago.
Improve this question
Pyhon allows to create any class instance attribute just like new variable and you don't need to define them in class definition.
What's the purpose of that?
class MyClass:
def __init__(self):
pass
obj = MyClass()
obj.a = '1';
print(obj.a)
#>> 1
P.S.
found interesting example of such kind of usage
Can you use a string to instantiate a class
There dynamically created attributes used to store dynamically instatiated classes
The purpose of this is simplicity: There is no difference to accessing an instance inside or outside of a method. The object seen inside and outside of a method is completely equivalent, and by extension the same rules apply anywhere:
class MyClass:
def __init__(self):
print(self) # <__main__.MyClass object at 0x119636490>
self.b = 12 # assign to an instance
obj = MyClass()
print(obj) # <__main__.MyClass object at 0x119636490>
obj.b = 12 # # assign to an instance
Note that one can read and write attributes inside and outside methods, and these attributes are visible inside and outside of methods. In fact, Python has no concept of "inside" and "outside" of methods, aside from a few code-rewrites such as double-underscore name mangling.
This is both a result and the enabling feature to allow various inbuilt features of other languages to work without explicit support. For example, Python allows the equivalent of extension methods without extra syntax/functionality:
class MyPoint:
def __init__(self, x, y):
self.x, self.y = x, y
# Oops, forgot a repr!
def my_point_repr(self):
return f'{self.__class__.__name__}(x={self.x}, y={self.y})'
MyPoint.__repr__ = my_point_repr
print(MyPoint(1, 2)) # MyPoint(x=1, y=2)

use functions in a class - 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 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)

Categories