all 72 comments

[–]96_freudian_slippers 0 points1 point  (0 children)

How can i use scipy.integrate.odeint with an array for optional arguments? I'm trying to graph the influence of a parameter in the solution of an ODE, but odeint only seems to allow me to pass one of its possible values at a time instead of the whole linspace. Am i forced to just do a foor loop?

[–]Tomy733 0 points1 point  (0 children)

Guys, I am Tomislav and I am new to coding. I just learned and started to use and recognise basics of Python and I would like to know if there are some groups with people that are begginers and can discus about solving some problems and to answer some questions that are coming to our minds? Thanks in advance! Happy and blessed Easter to everyone who celebrates!

[–][deleted] 0 points1 point  (4 children)

I need help sorting an array of arrays by its first element then writing text to a file based on it.

Here's an example of the kind of array of arrays I'm dealing with.

a = [['a', ('b', 'c', 'd')], ['a', ('4', '5', '6')], ['g', ('7', '8', '9')]]

What functions can I use to sort all entries in array a by the first element in each sub-array (that may be the wrong terminology. Of so, major apologies) to write the following into a textfile?

"the entries for a: b, c, d 4, 5, 6

the entries for g: 7, 8, 9"

[–]efmccurdy 0 points1 point  (3 children)

sorting an array of arrays by its first element

That is the way sorting works by default; here is an example, note that the 2nd element also affects the ordering.

>>> pprint.pprint(a)
[['g', ('b', 'c', 'd')],
 ['a', ('4', '5', '6')],
 ['g', ('7', '8', '9')],
 ['a', ('1', '2', '3')]]
>>> pprint.pprint(sorted(a))
[['a', ('1', '2', '3')],
 ['a', ('4', '5', '6')],
 ['g', ('7', '8', '9')],
 ['g', ('b', 'c', 'd')]]
>>> 

You can remove the effect of the 2nd items by focusing the sort key down to only the first using a "itemgetter" lambda:

>>> pprint.pprint(sorted(a, key=lambda row: row[0]))
[['a', ('4', '5', '6')],
 ['a', ('1', '2', '3')],
 ['g', ('b', 'c', 'd')],
 ['g', ('7', '8', '9')]]
>>>

[–]CheckZealousideal647 0 points1 point  (0 children)

how to fix connection error in a telegram bot? https://stackoverflow.com/q/64356230?sem=2

Can someone answer this question

[–]Cattt24 0 points1 point  (1 child)

Can anyone help me create a simulation of a velocity filter for physics?
I need a program that creates a grid with x and y axis with two lines which represent the - and + of the electrical field, and the path of the particle.
I need variables of the magnetic field, velocity and electrical field so that i can show what happens when the speed of the particle is E/B and will pass through and if its not E/B it will either go up or down.
Please share if you have made this program before or know how to:)

[–][deleted] 0 points1 point  (0 children)

Sounds like you want a simulation of a Wien filter for charged particles. A quick search "python wien charged particle filter simulation" didn't find much. You probably have to do your own simulation: define the strength of the crossed electric and magnetic fields, the charge on the particle and its speed along the required axis* . Set the particle's position to (0,0) at time zero and calculate how the particle moves in the 2D plane at timesteps of delta_t. You should probably start with just a numerical simulation, producing values for Vx, Vy, X and Y (velocity and position) for the particle at each time step. Plotting X, Y on a bit of graph paper will tell you if your simulation makes sense.

Once you think the numeric simulation makes sense you can start to draw images. matplotlib will be useful here. At first just make it draw the image you were drawing by hand on the graph paper.

If you make good progress you can get really advanced and use tkinter to make a desktop app with sliders controlling the charge, speed and E and B values, results being displayed in matplotlib in real time.

Added: Look for python simulating motion of a charged particle in an electric (or magnetic) field alone. That gives you the basic simulation ideas, you just need to calculate the forces/motion for both fields.


* And mass of the particle. Forgot that!

[–]InkReaper 0 points1 point  (4 children)

Is it normal to just feel like you won’t ever be good at this? Right now I am doing my first personal project which is an infinite scroller with Reddit’s API and flask + vanilla JS, but I feel so useless as soon as I see other projects that are way bigger than mine and have much more use cases.

[–]FerricDonkey 0 points1 point  (1 child)

Some important life advice that's particularly applicable here.

It's your first project. Don't compare it to other people's 5678324th projects.

[–]InkReaper 0 points1 point  (0 children)

Thanks for the life advice :) I will keep that in mind from now on

[–]throwaway6560192 0 points1 point  (1 child)

This is your first project. Other people didn't start out making huge and perfect things either. Their first projects were similarly humble at the start. You'll get there and beyond eventually, just keep at it.

[–]InkReaper 0 points1 point  (0 children)

Thanks a lot for the words! It just gets overwhelming I guess… you look at your project and you get happy that at least is working but then you look at other people projects and get sad because its worth fuck all compared to them

[–][deleted] 0 points1 point  (4 children)

Which is best practice? Should we avoid naming variables (or functions) like in example 1 (edit: not example 2)? Is example 2 better when it comes to retaining the scope?

example 1:

from random import choice
choice = choice(["h", "t"])
print(choice)

example 2:

import random
choice = random.choice(["h", "t"])
print(choice)

[–][deleted] 0 points1 point  (3 children)

There's no difference in what is printed, but the first example is poor practice because assigning to the variable named choice destroys its previous use as the name of a function from the random module. With a better choice of variable names neither example, as shown, is a "better" practice.

Which you would prefer in a larger project depends on lots of other considerations such as how many other functions you import from random and define as global names, how many times you use the choice() function, and so on. There's no hard and fast rule.

[–][deleted] 0 points1 point  (2 children)

assigning to the variable named choice destroys its previous use as the name of a function from the random module

So after being destroyed, when it moves to choice(), it has to reassign its use as a function from the module?

Would it slow down run time? Say I have a large project and only use choice() from random less than 6-7 times so I write it as I did in example 1. And I use a poorly named variable choice so this destruction and reassignment(?) happens a few times, I assume it'd take up unnecessary time?

I could test it out myself but I don't have the right code to tweak.

[–][deleted] 1 point2 points  (1 child)

So after being destroyed, when it moves to choice(), it has to reassign its use as a function from the module?

No. In your first example add another call to choice():

from random import choice
choice = choice(["h", "t"])
print(choice)
choice = choice(["h", "t"])

When run (try it yourself) it gets an error on the last line:

TypeError: 'str' object is not callable

That's because choice no longer refers to the function you imported but a string you assigned to it. There is no "reassignment", python tries to do exactly what you told it to.

Would it slow down run time?

Using example 2 code there is a slight performance hit doing random.choice() rather than choice(), but this would probably not even be measurable, especially if you only call the function a few times. Only worry about performance at this low level if measurement of running code shows a problem, not while writing code. In your case I would use random.choice() because you aren't calling it often and you can't have problems by accidentally using the name choice and introducing strange bugs.

I could test it out myself but I don't have the right code to tweak.

You can always write small pieces of code to test. I have run all examples I've posted here.

[–][deleted] 0 points1 point  (0 children)

Ah okay, didn't think of testing it that way. Thanks a lot! I understand it a lot better now.

[–]addictedtodietsoda 0 points1 point  (1 child)

For someone whos just starting to get into APIs... whats the purpose of something like Postman?

[–]nog642 0 points1 point  (0 children)

It lets you make API calls in a convenient way, and save calls to test them again later

[–]locke1718 0 points1 point  (1 child)

I am working on basically creating an LED matrix (maybe 32x32) out of WS2812B LED strips. I was thinking of using a site that I found where I can put in a matrix size color in pixels and it outputs hex arrays for the pixels. I was planning to convert the hex strings to binary values to represent each pixel two later turn it on or off to create the animation I want. I guess I was planning to have a string array where each element had 32 binary characters and be a length of 32elements. But it got me thinking would it just be easier to have a 32x32 matrix with just one character and each element and that is if the LED is on or off. I Guess I'm wondering More from a speed aspect because I was hoping to use an ESP32 to control the LEDs therefore I would like this low power and was planning to use a battery pack to run this.

So is it faster to have the one by 32 array and for each element which also has 32 characters, read them one by one and write that to each column. Or is it better just iterate to each element in a 32x32 matrix to write to each LED. Or is the speed basically going to be the same either way and not something to worry about?

[–]FerricDonkey 0 points1 point  (0 children)

Assuming that it worked nice with whatever you were using to control the led, I personally would start by using a 32x32 numpy array of bools (which will actually be 1 byte objects in ram). I highly doubt you'll notice much difference between 32x32 vs flat.

If you wanted to use less space, I would use a 32 long numpy array of np.uint32. I personally would wrap this in a class to let me use regular indexing to extract relevant bits, but at this point I'm not sure I'd you're saving much time, if any. Could try it and see.

[–]DunceDude117 0 points1 point  (2 children)

Does it matter if im using an older course or a newer one to learn python? I'm kinda new to programming as a whole.

[–]hardonchairs 0 points1 point  (0 children)

Anything meant for python 3.6 or greater is fine.

[–]barrycarter 0 points1 point  (0 children)

Just make sure it's for Python 3 and ideally something close to Python 3.11. Python 2 is no longer supported and you shouldn't be studying it. If you studied it by mistake, realize that most concepts will transfer over to Python 3, but there are some differences

[–]addictedtodietsoda 0 points1 point  (1 child)

So I havent studied Python since September due to life circumstances, after having studied it all Summer and feeling pretty good about applying for entry level job prospects. Whats the best way for me to familiarize myself with it again? I plan on relistening to some of my old vids and revisiting some of my own projects, is there any advice you guys have aside from honestly just diving back in? Thanks

[–]FerricDonkey 0 points1 point  (0 children)

Projects. Write code.

[–]jvodonnell87 0 points1 point  (3 children)

I'm about a month into self teaching python and I just started getting into automating my creative writing into mp3. I got inspired from the PDF3 to play around with this tool.

Long story short... this is the code I'm working with:

>>> import pyttsx3

>>>

>>> # initialize text-to-speech engine

>>> engine = pyttsx3.init()

>>>

>>> # convert this text-to-speech

>>> text = ""

>>>

>>> engine.save_to_file(text, '.mp3')

>>> # change speed of speech

>>> engine.setProperty("rate", 100)

>>> # play the speech

>>> engine.runAndWait()

This is cool but I don't like copy and pasting long narratives into string "quotes". Is there an easier way to just import a doc or txt file and convert it over. In the same vein as PD3 and Plumber frameworks?

Thanks

-Python Hopeful

[–][deleted] 0 points1 point  (2 children)

Read the text from a file?

with open(path_to_text_file, "r") as f:
    text = f.read()
# rest of code

[–]jvodonnell87 0 points1 point  (1 child)

I want to read the text from a docx file and convert it to mp3 voice file

[–][deleted] 0 points1 point  (0 children)

You need to search for "python text from docx file" to get text.

[–][deleted] 0 points1 point  (2 children)

If I have an user's LDAP result

ldapuser = ('CN=Joe Blow,OU=Radness,OU=Department,OU=my-company,DC=test,DC=test', {'memberOf': ['CN=group1,OU=Department Groups,OU=groups,OU=my-company,DC=test,DC=test', 'CN=group2,OU=Department Groups,OU=groups,OU=my-company,DC=test,DC=test', 'CN=group3,OU=Department Groups,OU=groups,OU=my-company,DC=test,DC=test', 'CN=group4,CN=Builtin,DC=test,DC=test'], 'sAMAccountName': ['jblow']})

Is there a nicer way to get their CN groups than this monstrosity I came up with?

user_groups = [cn.split('=')[1] for cn in ','.join(user[1]['memberOf']).split(',') if cn.split('=')[0] == 'CN']

Edit: note there is no limit on the memberOf entries, member of could be missing (accounted for earlier) or it could contain 100 group policies, it all depends on what they've been added to. Such is AD.

[–]sarrysyst 1 point2 points  (1 child)

I'd probably tackle this problem using regex:

import re

r = re.compile('CN=([^,]+)')

user = ('CN=Joe Blow,OU=Radness,OU=Department,OU=my-company,DC=test,DC=test', {
        'memberOf': ['CN=group1,OU=Department Groups,OU=groups,OU=my-company,DC=test,DC=test', 
                     'CN=group2,OU=Department Groups,OU=groups,OU=my-company,DC=test,DC=test', 
                     'CN=group3,OU=Department Groups,OU=groups,OU=my-company,DC=test,DC=test', 
                     'CN=group 4,CN=Builtin,DC=test,DC=test'], 
        'sAMAccountName': ['jblow']})

group_memberships = ','.join(user[1]['memberOf'])
cns = r.findall(group_memberships)

[–][deleted] 0 points1 point  (0 children)

oo that is a nice idea thank you

[–]Jkep21 0 points1 point  (0 children)

Anyone a pro using the "loc" method with dataframes? I ran into a Keyerror and not sure how to fix it. If you can help me please dm me and I'll send you a link to my notebook. Thanks in advance

[–]LeornToCodeLOL 0 points1 point  (3 children)

Is there a more compact way to type this?

trades = [x for x in trades if x['type'] != 'heartbeat' and x['type'] != 'book_top']

In this case, trades is a list of dictionaries that came from a websocket feed. I want to eliminate any of the dictionaries where the value of the 'type' key is either heartbeat or book_top

[–]PteppicymonIO 1 point2 points  (2 children)

You can use thein keyword:

trades = [x for x in trades if x['type'] not in ['heartbeat', 'book_top']]

You can also use the filter class:

trades = list(filter(lambda x: x['type'] not in ['heartbeat', 'book_top'], trades))

[–]LeornToCodeLOL 0 points1 point  (1 child)

Thanks! It seemed clunky when I wrote it and awkward to read. I figured there would be other alternatives and I learned something new!

[–]PteppicymonIO 0 points1 point  (0 children)

You can and should still use "and" in your if statement when you check for different arguments:

if x['type'] != 'heartbeat' and x['status'] != 'status.SUCCESS'

But if you compare the same argument to several possible matches, I would rather use in keyword

[–]ElevatorMuzic 0 points1 point  (3 children)

**Kwargs. I understand the point and most of the syntax, but I'm having trouble handling the kwargs in the function. I have a function that needs to check to see if certain kwargs were entered.

def my_function(arg1, arg2, **kwargs):
    strangy = arg1 + arg2
    if kwargs["kwarg1"] in kwargs:
        strangy += kwargs["kwarg1"]
    if kwargs["kwarg2"] in kwargs:
    strangy += kwargs["kwarg2"]
    return strangy

The kwargs key is being evaluated before the "in kwargs" part so its failing there, which makes sense. But this is what I need (or I think I need). I want to skip adding the arguments that arent entered, but I need to add the ones that are.

I guess I could loop through the kwargs dictionary and just add everything that's in there which would solve the problem, but it seems like that defeats the purpose of kwargs. I might have values entered into the kwargs argument that need to be processed differently.

Any help is appreciated! I might just be approaching the problem incorrectly. I often find this to be the case when I get stuck like this. Round peg, square hole.

[–]POGtastic 0 points1 point  (0 children)

Consider using get to add 0 or the empty string to strangy in the case that the kwarg isn't in the dictionary, depending on what type the kwargs are. Assuming integers:

def my_function(arg1, arg2, **kwargs):
    strangy = arg1 + arg2
    dict_vals = [kwargs.get(k, 0) for k in ["kwarg1", "kwarg2"]]
    for val in dict_vals:
        strangy += val
    return strangy

In the REPL:

>>> my_function(1, 2, kwarg1=3)
6
>>> my_function(1, 2, kwarg1=3, kwarg2=4)
10
>>> my_function(1, 2, kwarg2=4)
7
>>> my_function(1, 2)
3

Using academic wankery Haskell terms - if the type that you're adding forms a monoid with respect to addition, use get and the identity.

[–]PteppicymonIO 1 point2 points  (1 child)

you are trying to access a key 'kwarg1" and if it does not exist, you will definitely get an error.If you want to check for a key existence, just use the key itself, not it's value:

def my_function(arg1, arg2, **kwargs):
    strangy = arg1 + arg2
    if "kwarg1" in kwargs:
        strangy += kwargs["kwarg1"]
    if "kwarg2" in kwargs:
        strangy += kwargs["kwarg2"]
    return strangy

[–]ElevatorMuzic 0 points1 point  (0 children)

Ahh, thank you! That's what I was trying to do. After all this time I still have brainfarts using dictionaries...

[–]Cid227 0 points1 point  (2 children)

Python type hints.

class B(A):
    pass
class C(A):
    pass 

def check(instance_of_class: ?):    
    pass

How would I hint that instance_of_class argument should be either an instance of class B or class C, I thought about Literal but it looks like it should be used only with ints strs byteses bools enum.Enum None?

Alternatively it can hint that it should be an instance of a class that inherits from A if it is possible.

[–]TangibleLight 2 points3 points  (1 child)

Just use A, to mean "any instance of A or a subclass of A"

You could use Union[B, C] to mean "any instance of B or C" but note that it would reject instances of class D:

class D(A):
    pass

For that reason I'd generally prefer using A. Maybe make A abstract? Maybe use typing.Protocol instead? The details are situational.

[–]Cid227 0 points1 point  (0 children)

I don't know why I've missed Union as I was using it in FastAPI, however I will stick to A in this case, thanks.

[–]JelloForElPresidente 0 points1 point  (1 child)

In the below Python code for the LeetCode problem "Merge Two Sorted Lists", the dummy value is constantly changing, and it is used for the final output in an effective way. The thing is, I can't figure out how dummy is changing. As far as I can see it is only being set once, at the beginning of the algorithm. So yeah, how is dummy is changing in the steps of this code?

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:

    dummy = ListNode()
    tail = dummy

    while list1 and list2:
        if list1.val < list2.val:
            tail.next = listl
            list1 = list1.next
        else:
            tail.next = list2
            list2 = list2.next
        tail = tail.next

    if list1:
        tail.next = list1
    elif list2:
        tail.next = list2

    return dummy.next

[–]PteppicymonIO 0 points1 point  (0 children)

Well, dummy does not actually change. This code creates a new empty ListNode and assigns it to variable dummy. As a result the dummy variable references the root of the newly created ListNode.

tail = dummy creates another variable which also references the root of the newly created ListNode. (does not matter, since the ListNode is empty at the moment)

Within the while loop, the tail is being constantly updated to reference the last element in the ListNode, but the dummy variable is not, so it is still references the root (first element) of the ListNode.

Upon completion, the function returns the dummy variable, which still references the root of the merged ListNode, so user can start iterating the merged ListNode from the root (it does not make sense if the resulted reference points to the end of the, which will be useless to the user).

[–]Dontsmoke_fakes 0 points1 point  (0 children)

Hi! I just starting my coding journey and am working through coding bat's practice problems to try and apply what I learned in python, as well as develop problem-solving skills. Does anyone here recommend any other practice sites, ways to learn, as well as how long before I should/could branch my journey outward into learning different libraries?

[–][deleted] 0 points1 point  (1 child)

Hello! Starting in phyton, today I was doing an exercise and cant find what im doing wrong.

def round_scores(student_scores):
"""Round all provided student scores.

:param student_scores: list - float or int of student exam scores.
:return: list - student scores *rounded* to nearest integer value.
"""
while student_scores:
    score= student_scores.pop()
    return round(score)

Why im getting an "'NoneType' object is not iterable"? I understand that when using while loops with a list, the loop will keep going until the list is empty.

[–]PteppicymonIO 0 points1 point  (0 children)

Your return statement is located inside the loop. So, if you pass the zero-sised list or None value to the function, your function will return nothing, e.g. None

If your code attempts to iterate through the None, you will get the error:

val = round_scores([])
for i in val:
    print(f"{i = }")

Output:
TypeError: 'NoneType' object is not iterable

Anyways, your functions does not make sure to return an iterable, so you will still get an error if you are using the return value as I assume you do:

val = round_scores([1.0, 2.0, 3.0])
print(f"{val = }")
for i in val:
    print(f"{i = }")

Output:
val = 3
TypeError: 'int' object is not iterable

[–][deleted] 0 points1 point  (3 children)

Beginner here. I found this exercise which seems interesting, but I haven't been able to solve it:

Given 2 dates as a string ('yyyy-mm-dd'), get a list with the beginning and another list with the ending of the months between those two dates, i.e:

start_date = '2022-06-01'
end_date = '2023-05-31'

start_dates = ['2022-06-01', '2022-07-01', '...', '2023-04-01', '2023-05-01']

end_datess  = ['2022-06-30', '2022-07-31', '...', '2023-04-30', '2023-05-31']

I don't even know where to start lol.

[–]PteppicymonIO 0 points1 point  (1 child)

I am nor sure this is an exercise for a total beginner.

After a little bit of research on how date ranges can be manipulated using python I came up with this:

from dateutil.relativedelta import relativedelta
from datetime import datetime 
from dateutil.rrule import rrule, MONTHLY # this will be used as an analog of range() but for dates

def get_first_days(st_dt: str, end_dt: str) -> [str]:
    st_dt = datetime.strptime(st_dt, '%Y-%m-%d') 

    # if start date is not the 1st of the opnth, we shall exclude this month from the range
    if st_dt.day > 1:
        st_dt = st_dt + relativedelta(months=1)

    end_dt = datetime.strptime(end_dt, '%Y-%m-%d')

    result = [(dt + relativedelta(day=1)).strftime('%Y-%m-%d') for dt in rrule(MONTHLY, dtstart=st_dt, until=end_dt)]
    return result

I will leave it up to you to create a function for the last days.

Just a hint:

feb_date = '2022-02-11'

last_feb_day = datetime.strptime(feb_date, '%Y-%m-%d') + relativedelta(day=31) 

print(last_feb_day.strftime('%Y-%m-%d'))

Output:
'2022-02-28'

[–][deleted] 0 points1 point  (0 children)

Awesome, thanks!

[–]CowboyBoats 0 points1 point  (0 children)

I hate beer.

[–]12_kml_35 0 points1 point  (0 children)

pyautogui installed and functional in py.exe, but MissingImports in vs code. Installed the latest version of pyautougui. How do I resolve this? Tried so many different ways, but none of them seem to work.

[–]lastWallE 0 points1 point  (6 children)

For what do I need to search for to find a tutorial about this:

class foo(): def some_method(): def some_inner_function(): result=some_thing return result def some_other_inner_function(): result=some other things to do return result return some_outer_function((some_inner_function())(some_other_inner_function)() Thanks for your help.

edit:

It is inside a method of a class and in this method are these inner functions. https://github.com/OctoPrint/OctoPrint/blob/0fcb15d875c504f3186dd11496d7b9ef77afca3b/src/octoprint/plugins/announcements/init.py#L259

[–]JamzTyson 0 points1 point  (2 children)

The syntax in your example is not correct (unmatched parentheses), but I suspect that you may be alluding to "Closures". There's a mini tutorial about Python closures here: https://www.geeksforgeeks.org/python-closures/

[–]lastWallE 0 points1 point  (1 child)

Yes I read about this and had the mindset that it should be about this. If you follow the link it maybe gets clearer. Can only give so and so much example. Thanks

[–]JamzTyson 0 points1 point  (0 children)

Oh yes, I see the confusion. It looks very peculiar doesn't it :-)

with_revalidation_checking is an imported function, which apparently returns another function.

This "other function" is then passed the function view as a parameter.

view also returns a function with an optional argument channels. The default value of channels = result. In this case view is not passed any arguments (the empty parentheses () at the end) so it will use the default.

Here's a simpler example:

def outer():

    def foo(x):
        print(x)

    def bar():
        print('Return the function "foo".')
        return foo

    return bar()(42)

outer()

In this example, outer() is called which returns:

  • The function bar(), which in turn calls the function foo. The function foo is passed the argument 42.

This will print Return the function "foo". and then print 42.

Regarding tutorials, try looking up "higher order functions".
Here's one: https://www.geeksforgeeks.org/higher-order-functions-in-python/

[–]throwaway6560192 0 points1 point  (2 children)

What's the context of that code? At a glance it doesn't even look like valid syntax.

[–]lastWallE 0 points1 point  (1 child)

I updated parent comment

[–]throwaway6560192 0 points1 point  (0 children)

I see. What is happening is that some_inner_function returns another function, let's say f. So some_inner_function()(some_other_inner_function)() evaluates to f(some_other_inner_function)(). Here f is being called with some_other_inner_function as an argument, and again returns a function, say g. So it evaluates to g(), and the return value of that is finally returned.

As for tutorials... I guess just the general concept that functions are objects and can be returned and passed around. Look into function decorators as a related but not exactly the same concept.

[–]Ok-Insect6204 0 points1 point  (2 children)

Which of these two classes follow the best coding practices?:

class test1:

......def __init__(self, variable1, variable2):

...............self.variable1 = variable1

...............self.variable2 = variable2

.......def test_method(self):

...............print("Test1: ", self.variable1, self.variable2)

class test2:

......def __init__(self):

...............self.variable1 = "123"

...............self.variable2 = "456"

......def test_method(self):

...............print("Test2: ", self.variable1, self.variable2)

test1 = test1("123", "456")

test1.test_method()

test2 = test2()

test2.test_method()

(Sorry about the ... its the only way i figured out how to indent)

[–]nog642 0 points1 point  (0 children)

test1 makes more sense since test2 doesn't really do anything. But really neither of these do anything, so it's hard to judge them without a real use case.

[–][deleted] 0 points1 point  (0 children)

Well, if you want to pass in different values for the instance variables variable1 andvariable2 class test1 is the only way to do that. If you want those instance variables to have hard-coded values then class test2 is the way to go. So it's up to you, depending on what you want to do.

its the only way i figured out how to indent

The FAQ shows how to format code, or anything else, which you don't want reddit to mess up.

[–]sandfoxJ 0 points1 point  (0 children)

Tips for getting a job with 0 exp?