-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclasses.py
More file actions
63 lines (51 loc) · 1.36 KB
/
classes.py
File metadata and controls
63 lines (51 loc) · 1.36 KB
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
62
63
#Inherited class definition
class Animal:
def __init__(self, name):
self.name=name
#Overriden by the method in the child class
def get_long_name(self):
return f"{self.name} the Animal"
#Class definition
class Dog(Animal):
"""Simple model of a dog"""
#Constructor
#self argument is automatically passed by method call for every class method
#class properties are attributes and can be added to self at will
def __init__(self, name, age):
#Initializing the parent class
super().__init__(name)
#Assigning values to attributes
self.age=age
#Default value
self.breed = 'mixed'
def sit(self):
print(f"{self.name} is now sitting.")
def roll_over(self):
print(f"{self.name} rolled over!")
def get_long_name(self):
return f"{self.name} the Dog"
def set_name(self, name):
self.name=name
#Creating an instance and accessing attributes
dog = Dog('Jack', 6)
print(f"{dog.name} is {dog.age} years old.")
#Modifying attributes
dog.age=12
print(f"{dog.name} is {dog.age} years old.")
#Calling methods
dog.sit()
dog.roll_over()
#Using a getter and setter
dog.set_name('Clover')
print(dog.get_long_name())
#How to import classes
#Whole module
import classes
#Single class to namespace
from classes import Dog
#Multiple classes to namespace
from classes import Animal, Dog
#All classes directly to namespace
from classes import *
#Alias
from classes import Dog as d