If not having a value has a meaning in your program (e.g. an optional value), you should use None. That's its purpose anyway.
If the value must be provided by the caller of __init__, I would recommend not to initialize it.
If "" makes sense as a default value, use it.
In Python the type is deduced from the usage. Hence, you can change the type by just assigning a value of another type.
>>> x = None
>>> print type(x)
<type 'NoneType'>
>>> x = "text"
>>> print type(x)
<type 'str'>
>>> x = 42
>>> print type(x)
<type 'int'>
Answer from wierob on Stack OverflowIf not having a value has a meaning in your program (e.g. an optional value), you should use None. That's its purpose anyway.
If the value must be provided by the caller of __init__, I would recommend not to initialize it.
If "" makes sense as a default value, use it.
In Python the type is deduced from the usage. Hence, you can change the type by just assigning a value of another type.
>>> x = None
>>> print type(x)
<type 'NoneType'>
>>> x = "text"
>>> print type(x)
<type 'str'>
>>> x = 42
>>> print type(x)
<type 'int'>
Another way to initialize an empty string is by using the built-in str() function with no arguments.
str(object='')
Return a string containing a nicely printable representation of an object.
...
If no argument is given, returns the empty string, ''.
In the original example, that would look like this:
def __init__(self, mystr=str())
self.mystr = mystr
Personally, I believe that this better conveys your intentions.
Notice by the way that str() itself sets a default parameter value of ''.
Videos
Total curiosity, but is there a way I can do this better:
player_inputs = ["", ""]
I want to have a list of 2 strings, but the strings will be inputed later. I thought I could do this:
player_inputs = [str, str]
but that doesn't work, not sure why.
import random
def shuffle(string):
templist = list(string)
random.shuffle(templist)
return "".join(templist)
usablelower = chr(random.randint(97, 122))
usableupper = chr(random.randint(65, 90))
usablenum = chr(random.randint(48, 57))
rst = random.choice(usableupper)
rst1 = random.choice(usablelower)
rst2 = random.choice(usablenum)
pw = rst1 + rst + rst2 + rst + rst2 + rst1
pw = shuffle(pw)
print(pw)Hello, I was trying to code a random password generator yet I could not understand the "return "".join(templist)" part. What is the use of empty string here, what does it do and why this code require it?