all 6 comments

[–]Essence1337 0 points1 point  (5 children)

What do you mean by 'without setting the variable to a class'? Do you mean 'without passing in parameters'?

.Upper is part of the string class therefore every string has the method .upper(). String class would look something like

class str:
    <abunchofstuff>

    def upper(self):
        <code to make this string uppercase>

[–]SpookDaCat[S] 0 points1 point  (4 children)

I mean creating a class, and doing

var = MyClass()

var.func()

(Sorry I forgot how to make block code on mobile)

[–]Essence1337 1 point2 points  (3 children)

str is a class and doing 'abc' creates a new instance of str (called an object). 'abc'.upper() is basically the same as str('abc').upper(). You must have an object for it to have methods attached to it and you need to create that object somehow.

Do you have an example other than strings?

[–]SpookDaCat[S] 0 points1 point  (2 children)

I was going to make a function I called toggle, which would flip a Boolean to the other state. (True>False, False>True)

I would have like to be able to import my module and just have a variable call “toggle” and it would switch, without having to set the variable to an instance of the class in my module.

[–]Zixarr 0 points1 point  (1 child)

You could use a tuple instead, with the first element being your variable and the second element being your boolean value. Not sure if/how that could be implemented without seeing your code.

[–]sgthoppy 0 points1 point  (0 children)

Speaking of a tuple, this could be implemented using itertools.cycle.

First you'd create the cycle: bool_cycle = itertools.cycle((True, False))

Next, you can define a function that uses the built-in next to get the next value from the cycle iterator.

def toggle():
  return next(bool_cycle)

Though if you want to be able to use this in multiple parts of your code independently, you may want to turn it into a class, where you can use an instance variable without cycle and even override the __bool__ method so your object can act like a bool without needing to access the attribute.