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.
Related
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 :) )
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)
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.
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 6 years ago.
Improve this question
I created a class 'Employee' with two methods as below. I know that these instance methods cannot be accessed by class itself without the instantiation of objects.
But, how the following code works without any instantiation of object?
>>> class Employee:
def __init__(self,name):
self.name = name
def getName(self):
return self.name
>>> Employee('John Doe').getName() #how this code is working??
'John Doe'
I am not seeing any sign of instantiation of object in the code above. But it is working, how?
You do create an instance. That's what calling the class does, it creates an instance:
>>> Employee('John Doe')
<__main__.Employee instance at 0x1042bab48>
You don't have to store that instance to be able to use it in the same expression. By tacking on the .getName() attribute lookup and call to the result of the Employee('John Doe') part, you are simply chaining looking up the method and calling it into the same statement.
Assignment merely creates a new reference to the instance you just created so you can refer to the instance later; using that named reference later causes Python to retrieve the instance again for you to call the method on.
Compare the output of the following with the above creation of an instance:
>>> employee = Employee('John Doe')
>>> employee
<__main__.Employee instance at 0x1042bac68>
The only difference is that now I stored the result of creating the instance in a variable with the name employee. Using that name again results in the instance being echoed again.
To Python then, there is no difference between using Employee('John Doe').getName() and employee.getName(), both look up the attribute getName on the instance and then call it.
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)