Python pycharm learning code text record (5)
文章编号:Python学【2020】005号
日期:2020-02-16
文章为日常学习记录,以备温习使用,同时作为像我一样的新人学习使用,内容属于学习记录,版权归视频学习提供方。
以每天追无聊小说的心态,每天坚持学习码代码。
Python Class相关知识:
Python 面向对象(Class 类相关信息)
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def move(self):
print("move")
def draw(self):
print("draw")
Point = Point(10,20)
print(Point.x)
result
10
class Person:
def __init__(self, name):
self.name = name
def talk(self):
print("talk")
john = Person("john")
print(john.name)
john.talk()
result
john
talk
class Person:
def __init__(self, name):
self.name = name
def talk(self):
print("talk")
john = Person("john")
print(john.name)
Person.talk(john)
result
john
talk
class Person:
def __init__(self, name):
self.name = name
def talk(self):
print("talk")
john = Person("john")
print(john.name)
john.talk(john)
Traceback (most recent call last):
File “D:/pycharm/HelloWorld/app.py”, line 9, in
john.talk(john)
TypeError: talk() takes 1 positional argument but 2 were given
john
class Person:
def __init__(self, name):
self.name = name
#__init__()方法是一种特殊的方法,被称为类的构造函数或初始化方法,当创建了这个类的实例时就会调用该方法
self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。
def talk(self):
print(f"Hi, I am {self.name}")
john = Person("john")
print(john.name)
john.talk()
bob = Person("Bob Smith")
bob.talk()
john
Hi, I am john
Hi, I am Bob Smith
inheritance/继承:
class Mammal:
def walk(self):
print("walk")
class Dog(Mammal):
def bark(self):
print("bark")
pass
dog1 = Dog()
dog1.walk()
dog1.bark()
walk
bark
引入模块module
converters.py录入
def lbs_to_kg(weight):
return weight*0.45
def kg_to_lbs(weight):
return weight/0.45
app.py文件录入
#引入converters.py
from converters import kg_to_lbs
print(kg_to_lbs(450))
result
10000
utils.py录入
def find_max(numbers):
max = numbers[0]
for number in numbers:
if number > max:
max = number
return max
app.py文件录入
#引入utils.py module
from utils import find_max
numbers =[10,3,6,2]
max = find_max(numbers)
print(max)
result
10
packages
了解packages 功能,引用模块。
import random
for i in range(3):
print(random.randint(10,20))
result
14
18
15
import random
members = ['John','Mary','Bob','Mosh']
leader = random.choice(members)
print(leader)
result
Bob
import random
class Dice:
‘# dice 掷筛子’
def roll(self):
first = random.randint(1,6)
second = random.randint(1,6)
return first,second
dice = Dice()
print(dice.roll())
result
(1, 5)
import openpyxl:
import openpyxl as xl
wb = xl.load_workbook('transactions.xlsx')
sheet = wb['Sheet1']
cell = sheet['a1']
cell = sheet.cell(row=1,column=1)
#在学习该句代码时,由于import openpyxl库,版本不同,不能直接输入(cell(1,1))
print(cell)
for row_number in range(2,sheet.max_row + 1):
cell = sheet.cell(row=row_number,column=3)
print(cell.value)
==
<Cell ‘Sheet1’.A1>
5.95
6.95
7.95==