Skip to content

Commit 548ec80

Browse files
committed
class example, little fixes
1 parent 854f9c9 commit 548ec80

File tree

1 file changed

+32
-10
lines changed

1 file changed

+32
-10
lines changed

advanced/functions.md

Lines changed: 32 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,34 @@ username, password = login()
4444
That gets kind of messy if there are more than three values to return,
4545
but I have never needed to return more than three values. If you think
4646
you need to return four or more values you probably want to use [a
47-
class](../basics/classes.md) instead and store the values like
48-
`self.thing = stuff`.
47+
class](../basics/classes.md) instead.
48+
49+
For example, instead of this...
50+
51+
```python
52+
def get_new_info(username):
53+
print("Changing user information of %s." % username)
54+
username = input("New username: ")
55+
password = input("New password: ")
56+
fullname = input("Full name: ")
57+
phonenumber = input("Phone number: ")
58+
return username, password, fullname, phonenumber
59+
```
60+
61+
...you could do this:
62+
63+
```python
64+
class User:
65+
# you probably want to make many other user related things too, add
66+
# them here
67+
68+
def change_info(self):
69+
print("Changing user information of %s." % self.username)
70+
self.username = input("New username: ")
71+
self.password = input("New password: ")
72+
self.fullname = input("Full name: ")
73+
self.phonenumber = input("Phone number: ")
74+
```
4975

5076
## \*args
5177

@@ -240,19 +266,15 @@ There's nothing wrong with returning a tuple from a function, and you
240266
are free to do that whenever you need it.
241267

242268
We don't need `*args` and `**kwargs` for most of the functions we write.
243-
Often functions just do something and arguments are a way to change how
244-
they do that, and by not taking `*args` or `**kwargs` we can make sure
245-
that we'll get an error if the function gets an invalid argument.
246-
247269
When we need to make something that takes whatever arguments it's given
248270
or call a function with arguments that come from a list we need `*args`
249271
and `**kwargs`, and there's no need to avoid them.
250272

251273
I don't recommend using keyword-only arguments with functions like our
252-
`print_box`. It's easy enough to guess what `print_box('hello', '-')`
253-
does, and there's no need to deny that. It's much harder to guess what
254-
`move('file1.txt', 'file2.txt', True, False)` does, so using
255-
keyword-only arguments makes sense.
274+
`print_box`. It's easy enough to guess or remember what
275+
`print_box('hello', '-')` does, and there's no need to deny that. It's
276+
much harder to remember what `move('file1.txt', 'file2.txt', True, False)`
277+
does, so using keyword-only arguments makes sense.
256278

257279
## Summary
258280

0 commit comments

Comments
 (0)