python的类以及一些小知识点
1 class Person:
2 # 类属性
3 name = "张三"
4 age = 18
5
6 # 构造方法
7 def __init__(self, name, age):
8 self.name = name # 实例属性
9 self.age = age
10 print("__init__:")
11 print(name)
12 print(age)
13
14 # 实例方法(又称:普通方法),传递 "实例的属性",
15 def instance_method(self)://实例方法中参数必须写self
16 print("instance_method:")
17 print(self.name)
18 print(self.age)
19
20 # 类方法,传递 "类的属性"
21 @classmethod
22 def class_method(cls)://参数是类本身,在这里是Person类本身
23 print("class_method:")
24 print(cls.name)
25 print(cls.age)
26
27 # 静态方法,传递 "类的属性"
28 @staticmethod
29 def static_method():
30 print("static_method:")
31 print(Person.name) # 可以,但不推荐
32 print(Person.age)
33
34
35 if __name__ == '__main__':
36 p = Person("a", 12)
37
38 # 普通方法(实例方法)只能由 "对象" 调用
39 p.instance_method()
40 # Person.instance_method() # 报错
41
42 # 类方法,既可以由 "对象" 调用,又可以有 "类" 调用,且可以直接访问 "类属性"
43 print('------------------------')
44 p.class_method()
45 Person.class_method()
46
47 # 静态方法,既可以由 "对象" 调用,又可以有 "类" 调用,但不可以访问 "类属性"
48 print('------------------------')
49 p.static_method()
50 Person.static_method()
Python格式化输出两位小数:
1 #方法1: 2 print("%.2f" % 0.13333) 3 4 #方法2 5 print("{:.2f}".format(0.13333)) 6 7 #方法3 8 round(0.13333, 2)
Python中的pi:
import math
math.pi 即可