Python 30 天筆記(Ch2)

類別

1
2
3
4
5
6
7
8
9
10
11
12
class Dog():
name = 'Jon'
color = 'brown'


>>> Dog
<class '__main__.Dog'>
Dog 是一個類別

>>> Dog()
<__main__.Dog object at 0x00000174A8438D68>
Dog() 是一個物件

範例

1
2
3
4
5
6
class Dog():
name = 'Jon'
color = 'brown'

instance = Dog()
instance.name

繼承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Animal():
name = 'Amy'
noise = "Grunt"
size = "Large"
color = "brown"
hair = "covers body"
def get_color(self):
return self.color
def make_noise(self):
return self.noise

// Dog 繼承 Animal
class Dog(Animal):
name = 'Jon'


dog = Dog()
dog.make_noise()
dog.size = "small"
dog.color = "black"
dog.hair = "hairless"