What's the point of creating classes and self in python? [duplicate] - python

This question already has answers here:
When should I be using classes in Python?
(6 answers)
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 8 months ago.
What's the point of creating classes and self in python? Like:
class ThisIsClass(self):
def Func():
self.var+=1
ThisIsClass()
Is it necessary to use them?

It becomes necessary to pass self argument to the functions of your class. however, your code has several problems like the initialization of var variable. You need a constructor __init__ to create the variable, after that, you will be able to modify it:
class ThisIsClass:
def __init__(self, value=0):
self.var = value
def Func(self):
self.var+=1
c = ThisIsClass()
c.Func()
print(c.var)
In the above code, the class is instantiated as an object and stored in the variable c. You can assign an initial value to var by passing an argument to the object creation, like: c = ThisIsClass(89)
Output:
1

It has to do with the right structure of programming in python. No you dont need them 100% but if you want to have a nice and clean code I would propose you to get used of them. Also when the self is declared inside the brackets after the function name, that function can retrieve (and make available) the variable (self.variable) from and to wherever inside that class.

Related

my global can't change in the def of a class [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 3 years ago.
I define a varible, name 'Decisoin_name' and set -1 at first
and I try to change it in a def of a class
because I’d like to add 1 everytime when I call the def
but the system send me a message
"local variable 'Decision_name' referenced before assignment"
what can I do?
Would you give me a solution to fix it ? thank you
The following is my code
Decision_name = -1
class Decision_Dialog(QDialog):
def sendback(self):
Decision_name+=1
print(Decision_name)
self.close()
You can't change a global name from a class method directly, you need to declare it as a global variable beforehand:
class Decision_Dialog(QDialog):
def sendback(self):
global Decision_name
Decision_name += 1
Although if it does not need to be a global variable, you can take different routes e.g. make it a class variable and let each instance modify to it's need, or make it a instance variable by defining in __init__ and make necessary changes afterwards.
Also, you should be using snake_case for variable names e.g. decision_name.

Real word simulation of a Printer using Queue in Python [duplicate]

This question already has answers here:
What do __init__ and self do in Python? [duplicate]
(18 answers)
Closed 3 years ago.
I am going through the book "Problem Solving with Algorithms and Data Structures using Python"
In the chapter for Queues there is a printer simulation with the Printer class.
here is the definition of Printer class:
class Printer():
def __init__(self, ppm):
self.pagerate = ppm
self.currentTask = None
self.timeRemaining = 0
My question is that how are the instance variable not present in parameter but still defined (e.g. currentTask and timeRemaining)?
Is it a practice in Python and is there any other better way to do this?
From the documentation https://docs.python.org/3/tutorial/classes.html#class-objects
The instantiation operation (“calling” a class object) creates an
empty object. Many classes like to create objects with instances
customized to a specific initial state. Therefore a class may define a
special method named __init__(), like this:
def __init__(self):
self.data = []
Also Instance variables vs. class variables in Python
You don't need to pass values for all parameters. By writing self.variable_name we automatically create instance variables. They don't need to be initiated with passed values. You can initiate them with None values.

Define class functions in different source files? [duplicate]

This question already has answers here:
Define a method outside of class definition?
(5 answers)
Closed 4 years ago.
Is it possible (preserving all the class functionality) to write the class functions in separate files?
Below is an example:
TestClass.py:
class MyClass():
def __init__(self, param1=1, param2=2, param3=3):
self.param1, self.param2, self.param3 =param1, param2, param3,
def ClassFun1(self, param1=2):
return param1**2/self.param2
TestClass2.py:
def ClassFun2(self, param1=3):
return param1*3/self.param2
Next, following this answer, I compile both files (I am too lazy to use import), create a class variable and try to use ClassFun2:
x=MyClass()
x.myMethod=ClassFun2
x.myMethod(2)
As a result, I get an error, since self in ClassFun2 is treated as a parameter, rather than class itself:
AttributeError: 'int' object has no attribute 'param2'
Is it possible to split class definition into several source files? It is possible in C++ and this is actually very convenient when working as a team.
The variable x is an object of the class, not the class itself. You need to do:
x = MyClass
x.myMethod = ClassFun2
Notice that I didn't put () after MyClass. That returns the class itself, it doesn't return an instance of the class.
Then you need to create an instance to execute the method:
y = MyClass()
y.myMethod(2)

Are Class variables mutable? [duplicate]

This question already has answers here:
Class (static) variables and methods
(27 answers)
What is the difference between class and instance attributes?
(5 answers)
Closed 5 years ago.
If I define a simple class
class someClass():
var = 1
x = someClass()
someClass.var = 2
This will make x.var equal 2. This is confusing to be because normally
something akin to this like:
a = 1
b = a
a = 2
will leave b intact as b==1. So why is this not the same with class variables? Where is the difference? Can call all class variables mutable?
In a way the class variables work more like assigning a list to a=[1] and doing a[0]=2.
Basically the problem is how is x.var acessing someClass.var it must be something different then is used when two variables are set equal in python. What is happening?
var is a static class variable of someClass.
When you reach out to get x.var, y.var or some_other_instance.var, you are accessing the same variable, not an instance derived one (as long as you didn't specifically assigned it to the instance as a property).

Clarification regarding self [duplicate]

This question already has answers here:
When is "self" required?
(3 answers)
Closed 8 years ago.
In methods when is it necessary to use notation like self.variable_name? For instance, I know that in the constructor method it needs to be like
class A(object):
def __init__(self, name):
self.name = name
in order to give it an instance variable. However, what about in other methods? When do I need to put self in front of a variable name and when is it okay to just use a variable name?
You must always put a self as the first argument of an instance method. This is what you use to access the instance variables.
It is similar to this in other languages, but different in that it is required whereas other languages will often have instance variables in scope.
Whenever you are wanting to access attributes of the particular object of type A. For example:
def get_name(self): # here, whenever this method is called, it expects 'self'.
return self.name
When calling this method outside of the class scope, python has self passed implicitly.
example = A('d_rez')
example.get_name() # no arguments are passed, but self is passed implicitly to
# have access to all its attributes!
So to answer your question: You need to pass self whenever you define a method inside a class, and this is usually because there are some attributes involved. Otherwise, it could just be a static function defined outside the class if it doesn't pertain to a particular instance of class A.

Categories

Resources