-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathL #23 - Class & Object.py
64 lines (44 loc) · 2.01 KB
/
L #23 - Class & Object.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
57
58
59
60
61
## Day 23: Class & Object
## Concept: Creating a Class - To define a class, use the class keyword, and define the data points inside.
# Simple class with a property
class Person:
name = "John Wick"
## Concept: Creating an Object - o create a new object, simply reference the class you want to build the object out of
# Simple class with a property & an object instance
class Person:
name = "John Wick"
# creating an object instance
person = Person()
# accessing the class property
print(person.name) #output: John Wick
## Concept: Class Constructor - __init__() method. When we create a class without a constructor, Python automatically creates a default constructor for us that doesn’t do anything. Every class must have a constructor, even if it simply relies on the default constructor
"""
The __init__() function syntax is:
def __init__(self, [arguments])
1. The 'self' argument refers to the current object. It binds the instance to the init() method. It’s usually named “self” to follow the naming convention.
2. The init() method [arguments] are optional. We can define a constructor with any number of arguments.
"""
# Simple class constructor
class Person:
def __init__(self, person_name):
self.name = person_name
person1 = Person("Johnny Depp")
print(person1.name) # Johnny Depp
person2 = Person("Lora Akintson")
print(person2.name) # Lora Akintson
## Concept: Object Methods
# Simple class with custom method. 'self' is a must use argument in any method inside class.
class Person:
# class attribute
country = "England"
# instance attribute
def __init__(self, person_name, person_job):
self.name = person_name
self.job = person_job
# instance method
def intro(self):
print(f"{self.name} is a {self.job} from {self.country}")
person1 = Person("Johnny Depp", "Actor")
person1.intro() # Johnny Depp is a Actor from England
person2 = Person("Lora Akintson", "Doctor")
person2.intro() # Lora Akintson is a Doctor from England