Category:Python: Difference between revisions
Jump to navigation
Jump to search
Line 92: | Line 92: | ||
= Subclass = | = Subclass = | ||
< | <syntaxhighlight lang="python" line> | ||
# Parent class | # Parent class | ||
class Vehicle: | class Vehicle: | ||
Line 119: | Line 119: | ||
car = Car("Honda", "Civic", 4) | car = Car("Honda", "Civic", 4) | ||
car.display() | car.display() | ||
</ | </syntaxhighlight> |
Revision as of 00:16, 11 October 2023
buffering
Fix CLI buffering in Python with:
$ python -u foo.py | tee mylog.log
"-u" means unbuffered, or something
Virtual Environments
# Check Python version
python3 --version
# Check pip version
pip3 --version
# Install virtualenv
pip3 install virtualenv
# Install venv
sudo apt install python3-venv
# Navigate to your project directory
cd ~/my_project/
# Create virtual environment
python3 -m venv myenv
# Activate virtual environment
source myenv/bin/activate
# Now you can install packages
pip install <your-package>
# Deactivate when you're done
deactivate
What Libs Have I?
$ pip freeze --local blinker==1.6.2 click==8.1.7 flask==2.3.3 importlib-metadata==6.8.0 itsdangerous==2.1.2 Jinja2==3.1.2 MarkupSafe==2.1.3 werkzeug==2.3.7 zipp==3.16.2
Package Info
Datetime and Timestamp
from datetime import datetime, timezone
import pytz
print("When including time, use one of the following:")
ts = 0
good_dt = pytz.utc.localize(datetime.utcfromtimestamp(ts))
print(f'pytz.utc.localize(datetime.utcfromtimestamp(ts)) = {good_dt}')
ts = 0
good_dt = datetime.fromtimestamp(ts, timezone.utc)
print(f'datetime.fromtimestamp(ts, timezone.utc) = {good_dt}')
dt_with_tz = good_dt
good_ts = int(dt_with_tz.timestamp())
print(f'int(dt_with_tz.timestamp()) = {good_ts}')
now_dt = pytz.utc.localize(datetime.utcnow())
now_ts = int(now_dt.timestamp())
renow_dt = datetime.fromtimestamp(now_ts, timezone.utc)
print()
print(f'now_dt = pytz.utc.localize(datetime.utcnow()) = {now_dt}')
print(f'now_ts = int(now_dt.timestamp()) = {now_ts}')
print(f'now_dt = datetime.fromtimestamp(now_ts, timezone.utc) = {renow_dt}')
now_ts = int(pytz.utc.localize(datetime.utcnow()).timestamp())
print(f'now_ts = int(pytz.utc.localize(datetime.utcnow()).timestamp()) = {now_ts}')
import time
print(f'now_ts = int(time.time()) = {int(time.time())}')
Subclass
# Parent class
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display(self):
print(f"This is a {self.brand} {self.model}.")
# Child class
class Car(Vehicle):
def __init__(self, brand, model, doors):
super().__init__(brand, model) # Call the __init__ of the parent class
self.doors = doors
# Overriding the display method of the parent class
def display(self):
super().display() # Call the display method of the parent class
print(f"It has {self.doors} doors.")
# Testing the classes
vehicle = Vehicle("Toyota", "Camry")
vehicle.display()
car = Car("Honda", "Civic", 4)
car.display()
Pages in category "Python"
The following 7 pages are in this category, out of 7 total.