Skip to content

Commit 0a89461

Browse files
authored
练习面向对象的获取对象的属性和信息
1 parent 3bddbfa commit 0a89461

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

test19.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
'练习面向对象的获取对象的属性和信息'
5+
6+
__author__ = 'sergiojune'
7+
8+
import types
9+
10+
# 判断基本类型
11+
print(type('str'))
12+
print(type(12))
13+
print(type(12.36))
14+
15+
16+
def fn():
17+
print('fn----')
18+
19+
20+
# 函数类型
21+
print(type(fn))
22+
23+
print(type('d') == str)
24+
print(type(56) == int)
25+
print(type(fn) == types.FunctionType)
26+
27+
28+
class Animal(object):
29+
def run(self):
30+
print('run ------')
31+
32+
33+
animal = Animal()
34+
print(type(animal))
35+
# 内置函数类型
36+
print(type(abs))
37+
38+
39+
# 还可以使用isinstance函数来进行判断类型
40+
print(isinstance(123, int))
41+
print(isinstance('dd', str))
42+
# 判断对象类型
43+
print(isinstance([1, 2], list))
44+
print(isinstance({1: 2}, dict))
45+
print(isinstance(fn, types.FunctionType))
46+
print(isinstance(abs, types.BuiltinFunctionType))
47+
print(isinstance(animal, Animal))
48+
# 第二个参数可以写一个元组。里面的关系表示或
49+
print(isinstance([2, 3, 5], (list, tuple)))
50+
51+
52+
# 对对象的属性进行操作
53+
class MyDog(Animal):
54+
def __init__(self):
55+
self.x = 9
56+
57+
# 这个方法就是调用len函数时被调用的方法
58+
def __len__(self):
59+
return 100
60+
61+
def power(self):
62+
return self.x * self.x
63+
64+
65+
dog = MyDog()
66+
print(len(dog))
67+
# 获取实例的属性列表
68+
print(dir(dog))
69+
# 获取实例的属性
70+
print(getattr(dog, 'x'))
71+
# 可以设置默认值,当没有时就会返回默认值
72+
print(getattr(dog, 'high', 404))
73+
# 设置属性
74+
setattr(dog, 'high', 0.86)
75+
# 获取上述设置的属性
76+
print(getattr(dog, 'high', 404))
77+
# 还可以判断是否存在该属性
78+
print(hasattr(dog ,'x'))
79+
print(hasattr(dog, 'attr'))
80+
81+
# 还可以获得实例的方法
82+
print(getattr(dog, 'power'))
83+
p = getattr(dog, 'power')
84+
# 下面这个p相当于 dog.power
85+
print(p())

0 commit comments

Comments
 (0)