-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02_Class_Animal__Class_Syntax.py
56 lines (34 loc) · 2.1 KB
/
02_Class_Animal__Class_Syntax.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# A basic class consists only of the class keyword, the name of the class, and the class from which the new class inherits in parentheses.
# For now, our classes will inherit from the _object_ class.
# This gives them the powers and abilities of a Python object. By convention, user-defined Python class names start with a capital letter.
class NewClass(object):
# Class magic here
pass
# pass doesn’t do anything, but it’s useful as a placeholder in areas of your code where Python expects an expression.
# __init__()
# we start our class definition off with an odd-looking function: __init__(), required for classes, and it’s used to initialize the objects it creates.
# __init__() always takes at least one argument, self, that refers to the object being created. You can think of __init__() as the function that “boots up” each object the class creates.
class Animal(object):
def __init__(self, name):
self.name = name # let the function know that name refers to the created object’s name by typing self.name = name
"""
Python will use the first parameter that __init__() receives to refer to the object being created;
this is why it’s often called self, since this parameter gives the object being created its identity.
This is a Python convention; there’s nothing magic about the word self but it’s overwhelmingly common
to use self as the first parameter in __init__(), so you should use this so that other people will understand your code.
"""
class Animal(object):
def __init__(self, name):
self.name = name
zebra = Animal("Jeffrey")
print zebra.name # Jeffrey
# Access attributes of our objects using dot notation.
class Square(object):
def __init__(self):
self.sides = 4 # 4
my_shape = Square()
print my_shape.sides
# https://discuss.codecademy.com/t/what-does-it-mean-to-inherit-from-the-object-class/340587
# https://discuss.codecademy.com/t/what-is-the-difference-between-a-class-and-an-object/340593
# https://discuss.codecademy.com/t/what-is-self/340594
# https://discuss.codecademy.com/t/how-should-i-indent-my-code-to-create-a-new-animal-object/340595